正在做一个博客相关的后台
用的是
nodejs mongoose
{
"_id" : { "$oid" : "5a4245gdfh11514ccwegwr2re0" },
"id" : "5a57dfadfae453erw54rt33", "__v" : 0,
"article" : [{
"articleTitle" : "天气好",
"articleDate" : "2018-01-14",
"content" : "天气真好"
},
{
"articleTitle" : "天气不好",
"articleDate" : "2018-01-07",
"content" : "天气真不好"
}]
}
想在上面的集合中首先用id找到这个文档 然后向文档中article数组中articleTitle为天气好的数组添加一个名字是comment的数组,期望结果是
{
"_id" : { "$oid" : "5a4245gdfh11514ccwegwr2re0" },
"id" : "5a57dfadfae453erw54rt33", "__v" : 0,
"article" : [{
"articleTitle" : "天气好",
"articleDate" : "2018-01-14",
"content" : "天气真好" ,
"comment" : [{
"comment": "说的真好",
"date": "2018-01-14",
"userName": "lucy",
"id": "dad3fq4rqf4e4g5gsjki"
},{....}
]
},
{
"articleTitle" : "天气不好",
"articleDate" : "2018-01-07",
"content" : "天气真不好"
}]
}
网上搜了很多都没有找到根据数组某个条件添加的
其实就是想在某个文章根据文章标题找到文章然后在文章后面添加评论,或者数组结构设计有问题也可以指出
如何搜索和修改评论麻烦知道的也告诉一下
谢谢各位啦
自己尝试了好多遍试出答案了 贴出来方便需要的人
models.article.update({id:id,"article.articleTitle":articleTitle},{$push:{"article.$.comment":comment}},{upsert:true}, (err, data) => {})