我有一个名为用户的集合,用于存储用户的消息&信息。我想通过它的id将新对象添加到现有集合中。
我收到错误' TypeError:user.insert不是函数' - 我想我错过了什么....
以下是来自控制器的方法:
UserDataController.prototype.sendMsg = function (userID, messages_data, cb) {
if (userID) {
user.findOne({_id: userID},function(err, result){ //Object id=59e5e542a5ba05056c57d847
// insert to the collection with the object id
user.insert({_id: userID} ,messages_data,function(err, result){
if(err) return cb(err);
return cb(null, result);
});
});
}
};
以下是我希望得到的结果:
"sentmessages" : [{
"message_body" : "whatsup", // new object
"message_subject" : "whatsup",
"message_date" : "20/01/2017"
},
{
"message_body" : "whatsup", // new object
"message_subject" : "whatsup",
"message_date" : "20/01/2017"
}]
架构看起来像这样:
var sentmessages = new schema({
message_date: String,
message_subject : String,
message_body : String,
});
var UserSchema = new schema({
firstname: String,
lastname: String,
email: String,
sentmessages :[sentmessages] // here is were i want to add new objects
});
答案 0 :(得分:0)
得到它......需要使用$ push
UserDataController.prototype.sendMsg = function (userID, messages_data, cb)
{
if (userID) {
var message_fixesd_data = messages_data.sent_messages[0];
user.update({_id: userID},
{ $push: { sent_messages: {
message_body : message_fixesd_data.message_body,
message_subject: message_fixesd_data.message_subject,
message_date : message_fixesd_data.message_date
}
}
}, function (err, result) {
if(err)
{
return cb(err);
}
else
{
return cb(true, 'File was save successfully', result);
}
});
}
};