Mongoose更新查询不适用于嵌套对象
问题描述:
我有一个嵌套对象的模型,我想更新该文档的单个字段,但无法做到这一点。我无法理解为什么它不起作用。Mongoose更新查询不适用于嵌套对象
这是我model
var sampleItemSchema = new Schema({
id: {
type: String,
required: true
},
content: {
type: Object,
required: true
},
location: Object,
createdAt: {
type: Date,
default: Date.now
},
sample: {type: mongoose.Schema.Types.ObjectId, ref: 'Sample'}
});
这是我的文件之一。
{ createdAt: Thu Apr 21 2016 19:46:17 GMT+0200 (CEST),
__v: 0,
sample: 571911df9a97810c3f35d83d,
location: { city: 'Kildare' },
content:
{ images: [],
price: { currency: 'EUR', amount: 2000 },
createdAt: '2016-04-21T17:46:17.349Z',
category: { id: '2012', name: 'Animals | Ponies' },
body: 'Beaulieu Ginger Pop (Ben) is a 14 year old 13.2hh grey roan New Forest pony. He has a full green passport, is microchipped and is fully up...',
title: '13.2hh All rounder Gelding' },
id: '12123191',
_id: 571911e99a97810c3f35d845 }
在这里,我试过了。代码
我在这里只给一部分
models.SampleItem.find({
sample: sample
}, function(err, sampeItemList) {
console.log('Total sample: ', sampeItemList.length);
async.eachSeries(sampeItemList, function(item, next) {
item.content.body = "want to update this field";
item.save(function(err, updatedItem) {
console.log('Updated description...', index);
})
})
})
请看看。也许我做错了什么。
谢谢
答
猫鼬不允许你使用Object
的模式类型。而应将type
设置为Schema.Types.Mixed
。这会给你一个对象,你想要设置任何属性。
您可以看到所有有效模式类型in the Mongoose Schema Types documentation的列表。
(你可能想在location
字段更改为Schema.Types.Mixed
为好。)
它看起来像'item.content.body'不是在你提供的,试着下定义子对象架构中定义'content'在架构中。 – zacran
我给出了内容类型“对象”。存储对象是否是错误的?如果这是错误的,那么为什么数据存储? – abdulbarik