在mongodb文档模式中返回promise



我有以下问题:无法读取未定义的属性'then'。这是我的代码:

commentSchema.methods.saveIfMovieExist = function () {
const Comment = this;
Movie.findOne({imdbID: Comment.imdbID}).then(movie => {
if (!movie)
return Promise.reject();
return Comment.save();
}, err => {
return Promise.reject();
}); };

然后我有一个请求:

router.post('/', (req, res) => {
const comment = new Comment({
imdbID: req.body.imdbID,
text: req.body.text
});
comment.saveIfMovieExist(comment).then(doc => {
res.send(doc);
}, err => {
res.status(400).send(err);
});
});

我想检查是否存在imdbID的电影,如果存在,请在数据库中插入注释。我在连锁承诺中错过了什么,但不知道是什么。有什么想法吗?

您没有返回find函数,所以首先返回该函数,然后可以从中返回promise。

commentSchema.methods.saveIfMovieExist = function () {
const Comment = this;
return Movie.findOne({imdbID: Comment.imdbID}).then(movie => {
if (!movie)
return Promise.reject();
return Comment.save();
})
};

最新更新