2013-05-11 55 views
0

查詢貓鼬我有一個貓鼬模型,看起來像這樣:如何由是財產和數組項

var mongoose = require('mongoose') 
, Schema = mongoose.Schema; 

var PictureSchema = new Schema({ 
    listId: { type: Array, required: true }, 
    thumb: { type: String, required: true }, 
    large: { type: String, required: true } 
}); 

var Picture = module.exports = mongoose.model('Picture', PictureSchema); 

我將嘗試通過查找一個圖片在我的路由器來更新這個模型的實例「listId」屬性。像這樣:

app.put('/pictures/append', function(req, res) { 
    var targetListId = req.body.targetListId 
    , currentListId = req.body.currentListId; 

    Picture 
    .find({ listId: currentListId }, function (err, picture) { 
     console.log('found pic', picture); 
     picture.listId.push(targetListId); 
     picture.save(function(err, pic) { 
     console.log('pic SAVED', pic); 
     }); 
    }); 
}); 

「currentListId」是一個字符串,而listId是currentListId的數組。也許這不是查詢數組屬性的正確方法嗎? 我得到一個錯誤:

TypeError: Cannot call method 'push' of undefined 

就行了:

picture.listId.push(targetListId); 

但是,當我擡頭看圖片車型蒙戈,他們確實有listId陣列,而有些則包含該項目「currentListId」我正在使用我的查詢。

我試過使用$ elemMatch和$ in,但我不知道我是否正確使用它們。 任何想法,如果我只是寫我的查詢錯誤?

回答

0

在模式中指定Array類型字段相當於Mixed,它告訴Mongoose該字段可以包含任何內容。相反,改變你的架構是這樣的:

var PictureSchema = new Schema({ 
    listId: [String], 
    thumb: { type: String, required: true }, 
    large: { type: String, required: true } 
}); 
+0

非常感謝,這是我的問題的一部分。我還需要調整我的路由器更新代碼,如下所示:'.update({listId:{$ in:[currentListId]}},{$ push:{'listId':targetListId}},{multi:true},function err,data){console.log('Updated',data);});' – nicki9knuckles 2013-05-13 23:42:05

+0

@ nicki9knuckles好極了,歡迎來到SO。如果您的問題得到解決,您可以點擊答案左側的複選標記。 – JohnnyHK 2013-05-14 01:01:48