【问题标题】:adding an object of address to an array of addresses in MongoDB将地址对象添加到 MongoDB 中的地址数组
【发布时间】:2020-12-14 14:40:12
【问题描述】:

假设我有以下模型:

const User = mongoose.model('user', {
    addresses: [
        {
            address_name: {
                type: String,
            },
            country: {
                type: String,
        }
    ]
})

然后在我的 Rest Api 服务中调用 User 并更新用户的地址。

User.updateOne({
  "_id": user._id
}, {
  $push: {
    "addresses": {
      "address_name": A,
      "country": CountryA
    },
    {
      "address_name": B,
      "country": CountryB
    }
  }
})

所以首先地址数组是空的,然后我添加了一些地址。所以逻辑应该类似于将地址对象推送到地址数组。 它现在不适合我的方式。

【问题讨论】:

    标签: node.js mongodb mean-stack


    【解决方案1】:

    在这种情况下,我认为您可以将$push$each 结合使用。那就是当你有一个包含多个对象的数组要一次推送的时候。

    User.findOneAndUpdate({
        "_id": user._id
    }, {
        $push: {
            "addresses": {
                $each: [{
                    "address_name": "A",
                    "country": "CountryA"
                }, {
                    "address_name": "B",
                    "country": "CountryB"
                }]
            }
        }
    })
    

    Use $each with $push Operator.


    如果一次只有一个对象,那么:

    User.findOneAndUpdate({
        "_id": user._id
    }, {
        $push: {
            "addresses": {
                "address_name": "A",
                "country": "CountryA"
            }
        }
    })
    

    Append a Value to an Array.

    【讨论】:

    • 它不工作。没有错误,但只有一个和多个对象没有添加到 Db 中的数组中
    • 什么意思,所以只有一个对象被推送?请注意,address_namecountry 必须是 String,这取决于您的模型,例如 "CountryA" 等。也请尝试使用 findOneAndUpdate。编辑了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多