【问题标题】:Duplicate object in MongoDB array using Mongoose使用 Mongoose 在 MongoDB 数组中复制对象
【发布时间】:2022-01-21 07:26:50
【问题描述】:

我有一个 Node.js 应用程序,它在数据库中的“建筑物”下创建一个“单元”,该应用程序在“建筑物”中包含的数组中保存了两个“单元”。这两者在数据和创建的时间戳上都是相同的。任何人都知道为什么下面的代码会导致这种情况发生?我对此有点困惑。我不明白如何将两个对象添加到数组中。代码没有运行两次,我用 console.log() 进行了检查,只是查看了我的 API 日志。

await Building.findOneAndUpdate(
        {buildingID},
        {"$push": {units: unitData}},
        (err, doc) => {
            if(err) {
                logger.error(`POST unit/new save error for unit: ${unitID} - error message: `, err)
                return res.json({success: false, err, message: 'Error saving new unit, please try again'})
            }   
            logger.debug('POST unit/new save() doc: ', doc)
            return res.json({success: true, message: `Successfully saved new unit with ID of: ${unitID}`, unitData})
        }
)

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    我最终弄清楚了,当有等待和回调时,它将保存数据两次。这是 MongoDB 文档中记录的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-21
      • 1970-01-01
      • 2016-02-08
      • 2021-09-01
      • 2021-06-04
      • 2014-05-13
      • 1970-01-01
      • 2019-05-29
      相关资源
      最近更新 更多