【问题标题】:How can I accessed upsertedId when using updateOne in MongoDB在 MongoDB 中使用 updateOne 时如何访问 upsertedId
【发布时间】:2020-11-24 12:37:36
【问题描述】:

我有新数据要插入到我的 arrayblog 中(我的集合如下所示 - 如下所示):-

{
    _id: 0,
    // other vars here...,
    blog: [
        {
            _id: 0,
            title: 'Article 1'
        },
        // add new article here
    ]
}

现在我可以在我的blog array 中添加新的article,代码如下所示:-

const query = {}
const update = { $push: { blog: inputData } }
const options = { upsert: true }

All.updateOne(query, update, options)
.then(result => {
    res.redirect(`/article/${result.upsertedId}`) // read MongoDB documentation that I can get the newly inserted data ID by using result.upsertedId
})
.catch(err => res.redirect(`/`)

但我似乎无法将新插入的数据的ID 放入我的集合中。使用result.upsertedId 会返回undefined。根据上面的代码,我需要ID 才能将用户重定向到ID 的新文章页面。

这里的文档告诉它会 return upsertedId updateOne

这是我在 console.log 时得到的 result(里面没有 upsertedId

【问题讨论】:

    标签: arrays mongodb save insert-update upsert


    【解决方案1】:

    打印您的结果以确认已收到 ID,您的结果可能与此类似:

    { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
    

    您可以尝试使用 collection.findOneAndUpdate 并从该结果中检索 upsertedId

    【讨论】:

      【解决方案2】:

      需要在选项中通过new:true来获取更新文档的id 即

      const query = {}
      const update = { $push: { blog: inputData } }
      const options = { upsert: true, new: true  }
      
      All.updateOne(query, update, options)
      .then(result => {
          //result is your upserted document
          console.log("Upserted document : ", result);// try getting your upserted _id 
              //from this result 
          res.redirect(`/article/${result.upsertedId}`) // change //result.upsertedId into result._id or result.id whatever you get into //your result
      })
      .catch(err => res.redirect(`/`)
      

      【讨论】:

      【解决方案3】:

      不适用于嵌套文档。

      你正在做的是一个更新操作。

      医生说

      由 upsert 操作插入的文档的 _id 值。此值仅在启用 upsert 选项且更新查询不匹配任何文档时出现。

      您的查询会导致更新操作。这就是您收到nModified 的原因。

      一个选项是您可以将findOneAndUpdate 与选项returnNewDocument 选项一起使用。

      【讨论】:

      • 这个返回给我whole 集合数据。但不是新插入的数据。应该是这样的吗?
      • 不,你是怎么尝试的?它只会返回更新的文档?
      • 我将const options = { upsert: true } 更改为const options = { returnNewDocument: true }。而console.log(result),它给了我整个集合,但没有更新/新创建的数据。是因为我嵌套了文档吗?这就是为什么它会返回整个文档而不仅仅是博客数组。
      • 可以粘贴查询结果吗?
      • 它基本上给了我收藏中的所有东西(就像我的问题中提到的收藏示例)_id: 0, some other vars..., blog: [ {_id: 0, some other vars here...}, {_id: 1, some other vars here...}, {_id: 2, some other vars here...}]。除新/更新文档外的所有文档
      猜你喜欢
      • 1970-01-01
      • 2022-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-19
      • 2021-01-03
      • 2020-08-29
      • 1970-01-01
      相关资源
      最近更新 更多