2016-04-21 91 views
0

我有一個嵌套對象的模型,我想更新該文檔的單個字段,但無法做到這一點。我無法理解爲什麼它不起作用。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); 
    }) 
}) 
}) 

請看看。也許我做錯了什麼。

謝謝

+0

它看起來像'item.content.body'不是在你提供的,試着下定義子對象架構中定義'content'在架構中。 – zacran

+0

我給出了內容類型「對象」。存儲對象是否是錯誤的?如果這是錯誤的,那麼爲什麼數據存儲? – abdulbarik

回答

0

貓鼬不允許你使用Object的模式類型。而應將type設置爲Schema.Types.Mixed。這會給你一個對象,你想要設置任何屬性。

您可以看到所有有效模式類型in the Mongoose Schema Types documentation的列表。

(你可能想在location字段更改爲Schema.Types.Mixed爲好。)