Mongodb 如何将obj插入数组Mongoose
我有这个模式Mongodb 如何将obj插入数组Mongoose,mongodb,mongoose,Mongodb,Mongoose,我有这个模式 var postSchema = new Schema({ category: 'Home', body: 'sometext', comments: [{ nickName: 'Meron', comment: 'Hello', date: 'Feb 2 2017, 23:32', commentUnders: [{ nickName: 'Sto
var postSchema = new Schema({
category: 'Home',
body: 'sometext',
comments: [{
nickName: 'Meron',
comment: 'Hello',
date: 'Feb 2 2017, 23:32',
commentUnders: [{
nickName: 'Storseses',
comment: 'It's our dat',
date: 'Feb 5 2017, 22:03'
}]
}]
});
我如何查找和更新评论?我已经在评论中有一条评论id为5897518c0a913a842cc041cf。我尝试了这个解决方案,但不起作用:
Post.findByIdAndUpdate( {'comments._id': '5897518c0a913a842cc041cf'},
{
$push: {
commentUnders: {
"comment" : "Так, что мне делать-то?",
"nickName" : "Great",
"date" : Date.now()
}
}
}, function(err, data) {
if (err) {console.log(err); }
console.log(data);
});
使用with函数而不是更新匹配的注释数组:
您是否定义了这样的模式?或者您的文档就是这样的?{u id:ObjectId5896f719c89d211c25ab2787,类别:'Home',注释:[{comment:'Hello',昵称:'Meron',_id:ObjectId5897518c0a913a842cc041cf,commentUnders:[],日期:ISODate2017-02-05T16:23:40.018Z}],body:'sometext',日期:ISODate2017-02-05T09:57:45.877Z,_v:0}看起来是这样的
Post.findOneAndUpdate(
{ "comments._id": "5897518c0a913a842cc041cf" },
{
"$push": {
"comments.$.commentUnders": {
"comment" : "Так, что мне делать-то?",
"nickName" : "Great",
"date" : Date.now(),
}
}
},
function(err, data) {
if (err) console.log(err);
console.log(data);
}
);