【发布时间】:2017-09-18 04:48:56
【问题描述】:
我正在使用 mongoose 来处理 MongoDB。
我有以下文件
Posts:Array
0:Object
_id:58f9b2c903110b2c543fb7d1
postName:Test1
postText:Test2
postCount:0
status:true
我想做一个 HTTP 请求,根据 postName 更新或插入一个对象到这个数组。
例如,如果我通过以下内容
{
postName:Test1
postText:Test3
postCount:50
status:false
}
比 postName 匹配,我希望它只更新 postText、postCount 和状态。 如果 postName 不匹配数组中的任何一个对象,我希望它插入一个新对象。
这个问题可能与旧问题重复,我搜索并找不到答案。 我也尝试使用 $setOnInsert 但无法正常工作。
【问题讨论】:
-
使用这个
db.collection.update( <query>, <update>, { upsert: true } ) -
什么是
?我怎样才能使它基于postName?谢谢 -
db.collection.update({postName:Test1}, { postName:Test1 postText:Test3 postCount:50 status:false }, { upsert: true })
-
我了解,我可以对查询进行此更新吗?例如 db.collection.findOne({ _id: id }).update(...) 所以我会在一个特定的文档上做?
标签: arrays node.js mongodb mongoose