我有一段这段代码不起作用。我尝试用ObjectId
修改用户文档后(通过将其添加到数组中)来保存它。但是,user.save()
永远不会执行(我知道这是因为文档在db中不会更改),回调/承诺也不会执行。 Voot
被保存。
我尝试调整回调和诺言,但是没有成功。有谁知道该怎么办?
代码如下:
(为避免混淆,请注意handleError()
和sendJson()
函数是我制作的自定义函数)
// Create new voot
var newVoot = Voot({
title,
body,
user: userId,
is_public,
create_date
});
newVoot.save().then((voot) => {
User.findById(userId, (err, user) => {
handleError(err, 400, res);
if (user) {
user.voots.push(voot._id);
// This console log shows me the correct modified user document
console.log(user);
user.save().then(() => {
// This console.log and sendJson does not get executed
console.log("User object is saved");
sendJson(200, {voot}, res);
}).catch((err) => {
// This console log does not get executed
console.log(err);
});
}
})
});
答案 0 :(得分:0)
User.findById(userId, (err, user) => ...
在其回调函数中有两个参数:err
和user
。
user
是从MongoDB返回的文档,这意味着它是普通的Javascript对象,因此您不能在其上调用.save()
。
对于此用例,您可以使用Mongoose的findbyIdAndUpdate(),它将完成User
模型所需的两项操作。只要记住要给{ upsert: true }
作为选项对象,以确保您创建新文档(如果尚不存在)。
示例
User.findByIdAndUpdate({ id }, { update1: 'value' }, { upsert: true }, (err, result) => {
// handle result
})
答案 1 :(得分:0)
使用猫鼬更新方法代替使用select和之后的保存。这样的东西:User.update({_id:userId},{$ push:{voots:voot._id}})。然后...