首页 > 解决方案 > 如何将数组添加到存在于 mongodb 对象中的另一个数组中

问题描述

这是我的架构

    const CustomerSchema = mongoose.Schema(
  {
    name: {
      type: String,
      trim: true,
    },
    purchased: {
      modelsId: [{
        type: mongoose.Schema.ObjectId ,
        trim: true,
      }],
      collectionsId: [{
        type: mongoose.Schema.ObjectId,
        trim: true,
      }]
    }
  },
  { timestamps: true }
);

我想用猫鼬将一个数组添加到购买对象中的modelsId数组中

Customer.findOneAndUpdate({ _id: customer._id }, { $addToSet: { 'purcased.modelsId': { $each: modelsId } } }, 
{ new: true }).then(res => {
                        console.log('response', res)
                    }).catch(e => {
                        console.log('error', e)
                    })

它不工作!感谢您的帮助!

标签: node.jsmongodbmongoose

解决方案


看起来你可能只是有一个简单的拼写错误?尝试更改'purcased.modelsId''purchased.modelsId'. 我想你只是少了一个“h”!


推荐阅读