mongoose 如何更新内嵌数组对象的数据?
折腾了一晚上,文档看完了,谷歌操作一顿,没搞定。只能求助大神啦。
我有一个数据表 Schema 大概如下:
// PostCountry 表 const PostCountrySchema = new Schema({ uid: { type: ObjectId, ref: 'User', index: true, required: true }, pid: { type: String, ref: 'Product', index: { unique: true }, // 设为唯一的 required: true }, country_list: [ { country_name: { type: String, required: true }, country_code: String, fourPx_code: { type: String, default: '' }, declared: { // 申报单价 type: Number, default: 0 }, fourPx_send_name: { type: String, default: '' } } ] }
数据示例如下:
// PostCountry 表 "country_list": [ { "country_name": "China", "declared": 3, "fourPx_send_name": "中国邮政" }, { "country_name": "Ecuador", "declared": 21, "fourPx_send_name": "中国邮政" }, { "country_name": "Argentina", "declared": 14, "fourPx_send_name": "中国邮政" } ], "pid": "5380578836639", "uid": "5f7205b75e08ebr1dab5abfa"
我现在需要更新 PostCountry 表中嵌套数组的,fourPx_send_name 数据,如果数据存在则更新,如果不存在则在这个表内增加新的数组。
我 post 填充的数据是:
{ "country_name": "Canada", "declared": 123, "fourPx_send_name": "中国邮 31231 政", "pid":"5380578836639" }
我用过的方法 1:
const Data = await PostCountrySchema.findOneAndUpdate({ uid: ctx.cookies.get('uid'), pid: psotData.pid, country_list: { $elemMatch: { country_name: psotData.country_name } } }, { $set: { 'country_list.$.fourPx_send_name': psotData.fourPx_send_name, 'country_list.$.declared': psotData.declared } }, { new: true, upsert: true, setDefaultsOnInsert: true }) .then((data) => { return data }) .catch(err => console.error('返回错误' + err))
这样操作会返回一个错误 MongoError: Updating the path 'country_list.$.fourPx_send_name' would create a conflict at 'country_list'
我用过的方法 2:
const Data = await PostCountrySchema.findOneAndUpdate({ uid: ctx.cookies.get('uid'), pid: psotData.pid, 'country_list.country_name': { $ne: psotData.country_name } }, { $addToSet: { country_list: { country_name: psotData.country_name, fourPx_send_name: psotData.fourPx_send_name, declared: psotData.declared } } }, { new: true, upsert: true, setDefaultsOnInsert: true }) .then((data) => { return data }) .catch(err => console.error('返回错误' + err))
这样操作,如果 country_name 字段名字没搜索到,是可以添加成功的,然而再次提交修改就会报错了:
MongoError: E11000 duplicate key error collection: shopify.post_country index: pid_1 dup key: { pid: "5380578836639" }
操作 3,将 上面的 $addToSet 改成$push 结果也是一样,没有数据可以填充,有数据就无法填充了。
如何才可以根据条件更新内嵌数组的数据,如无数据则新增数组,如果有数据则更新数组?
折磨了半天了,求大神支个招吧。