【问题标题】:Adding an object to an array using mongoose if value not found, otherwise updating fields如果未找到值,则使用 mongoose 将对象添加到数组中,否则更新字段
【发布时间】: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


【解决方案1】:

正如 Veeram 在 cmets 中回答的那样,

答案可以在这里找到

PyMongo Update document with multiple records

在单个查询中无法插入嵌入的数组文档

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多