【问题标题】:append object to array of objects in mongoDB using mongoose使用 mongoose 将对象附加到 mongoDB 中的对象数组
【发布时间】:2021-06-04 21:04:38
【问题描述】:

这是我在猫鼬中的架构

const companySchema = new mongoose.Schema({
    country: {
        type: String,
        required: true
    },
    username: {
        type: String,
        unique: true,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    vaccine: [{
        name: String,
        price: Number,
        availibility: Number,
        needed: Number
    }]

}, {
    timestamps: true
});

我创建了一个表单,它提供疫苗对象的输入(名称价格可用性和需要),其数据可在 req.body 中获得。如何使用猫鼬附加它?

【问题讨论】:

  • 如果您需要更新数组中除插入之外的特定对象,请通知我

标签: node.js database mongodb mongoose backend


【解决方案1】:

只需使用 findOneAndUpdate() :

let vaccine ={ ... } // you object trying to add
let filter = { ... } // your filter you are trying to target the collection

Company.findOneAndUpdate(filter, { $addToSet:  {vaccine: vaccine}})

如果您想获得更新后的结果,只需使用 {new :true}。

完整示例:

let company = await Company.findOneAndUpdate(filter, { $addToSet:  {vaccine: vaccine}}, {new:true})

【讨论】:

    猜你喜欢
    • 2021-07-04
    • 2021-09-01
    • 2020-10-27
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 2020-08-15
    • 1970-01-01
    • 2020-07-31
    相关资源
    最近更新 更多