通过这个教程学习了解到是用.findAndModify()方法可以实现,并且通过命令行操作也实现了,但是在node项目中怎么写呢?
2016.9.8更新------------------------------------------------------------------------------
为什么给movie的id赋值的时候调用newID函数获取不到值呢?执行的时候newID("movieId")总是等于undefind,貌似在数据库查询没有返回的时候下面的JS就执行了。如果不用函数,直接把else部分写在.findAndModify()的callback里就能正常获取到值。
如果一定要用下面这种写法,newID("movieId")怎么才能获取到值呢?
function newID(indexName){
Counter.findAndModify(
{_id: indexName },
[],
{$inc:{count:1}},
{new:true},
function (err,obj) {
console.log(obj)
可以获取到obj.value.count,怎么写才能返回到外部函数?
}
怎么写能返回给函数?
}
app.post('/admin/movie/new',function (req, res) {
略...
if(id !== 'undefined'){
略...
}else{
_movie = new Movie({
_id:newID("movieId"),
title:movieObj.title,
doctor: movieObj.doctor,
country: movieObj.country,
year:movieObj.year,
poster:movieObj.poster,
language:movieObj.language,
flash:movieObj.flash,
summary:movieObj.summary
})
_movie.save(function (err, movie) {
if(err){
console.log(err)
}
res.redirect('/movie/'+ movie._id)
})
);
}
});
I would like to ask first, does the self-increment you are talking about have to be 1, 2, 3, 4...? Because the default
ObjectID
is actually auto-incremented. Using number sequences has its limitations, I explained why in this question.Official documents also have instructions on this issue.
Your problem does not lie in how to use the driver itself, but in your incorrect understanding of event drivers.
My approach is to add a variable. . .