如何更新discussionReplay中的值。三人评论,评论,评论所有者。我可以使用User.findOne方法找到用户。这样可行。但现在我需要找到匹配“discussionId”的正确讨论并更新讨论的discussionReplay值。
//mongoose schema
var UserSchema = new mongoose.Schema({
name: String,
discussions: [{
title: String,
discussionsId: String,
discussionReplay: {
comment: String,
commentImg: String,
commentOwner: String
}
}]
});
//route
var comment = req.body.comment;
var userId = req.body.UserId;
//this part work. here i find the user from user's discussion id.Here is fine
User.findOne({discussions: {$elemMatch: {discussionsId: req.params.id}}},function (err, theUser) {
//here i want to push comment,commentImg, commentOwner. But i just doesn't work
theUser.findByIdAndUpdate(userId,function(err,data){
data.discussions: {$elemMatch: {discussionsId: req.body.id},
{$push: {comment: comment, commentImg: "some/location/..." , commentOwner: 'some username'}}}
})
});
答案 0 :(得分:0)
您可以简单地修改从find()返回的对象,并在之后调用它的.save()方法。
User.findOne({<criteria>}).then(theUser => {
theUser.property.subpropertyarray.push(<new value>);
return theUser.save();
}
答案 1 :(得分:0)
这对我有用。这不会像.save方法那样刷新整个用户Schema,因此密码不会再次加密。
var toInsert = {comment: "someComment", commentOwnerName: 'someName'};
User.update(
{ _id: req.body.userId, discussions: { $elemMatch: { discussionsId: req.params.id } } },
{ $addToSet: { 'discussions.$.discussionReplay': toInsert } }, function(){})