2015-05-28 120 views
0

返回我使用的NodeJS表達貓鼬創建應用程序時增加新的屬性對象的數組。而mongodb.user是貓鼬的架構模型,我試圖獲取對象的用戶數組,該查詢是完美的,我的問題是我要添加新的屬性爲每個用戶。我嘗試如下。但它不會增加收藏。節點JS從貓鼬收集

exports.memberlist = function(req, res) { 
     user.find({}).exec(function(err, collection) { 
      collection.forEach(function(member){ 
      member.city = 'Colombo'; 
      collection.push(member); 
      }); 
     res.send(collection); 
     }); 
}; 
+0

您正在推進您正在迭代的集合。它是否取代現有的項目? – gypsyCoder

+0

用戶集合中沒有稱爲城市的項目。我想添加具有價值的新項目。 –

回答

0

默認情況下,貓鼬不允許添加從MongoDB DB提取的對象的屬性。爲此,您有兩種選擇:

1/ before exec statement you add a lean() method : 
user.find({}).lean().exec(function(err, collection) {do whatever you want with collection} 

2/ collection = collection.toObject(); 
+0

這很酷。它正在工作......感謝你的幫助Adil .. –

1

就可以像在架構層面這

創建控制器級別創建虛擬財產

userSchema.virtual('city').get(function() { 
    return 'Colombo'; 
}); 

exports.memberlist = function(req, res,next) 
{ 
    user.find({}).exec(function(err, users) 
    { 
if(!err) 
{ 
res.json(200, users.toObject({virtual: true})); 
} 
else 
{ 
next(err); 
} 

    }); 
}; 
+0

謝謝你的回答。但實際上我想通過查詢循環內的另一個集合來設置城市元素。 –

+0

你可以使用Model.update(條件,更新,選項,回調);你可以在選項設置多:真它將更新所有的文件做任何變薄之前添加到外地模式 – HDK

+0

exports.memberlist =功能(REQ,RES) { user.find({})EXEC(函數(ERR。 ,集合) { collection.forEach(功能(部件) { \t subscriptions.find({member._id}, '城市',功能(ERR,訂閱){ \t \t member.city = subscription.city; \t collection.push(構件); \t}); }); res.send(集合); }); };這裏的訂閱是另一種貓鼬模型,我想從特定用戶獲得城市和 其添加到成員對象。 –