【问题标题】:How to add new object by id to mongoDB collection?如何通过 id 将新对象添加到 mongoDB 集合?
【发布时间】:2017-12-25 23:48:17
【问题描述】:

我有一个名为 Users 的集合,用于存储用户的消息和信息。我想通过它的 id 将新对象添加到现有集合中。

我收到一个错误“TypeError: user.insert is not a function” - 我想我错过了什么......

这是来自控制器的方法:

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
});

【问题讨论】:

  • 据我了解,您想更新现有记录(以便将消息附加到用户的已发送消息列表中),而不是创建新记录。在这种情况下,您为什么使用插入而不是更新?我想你应该看看mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate
  • @TsvetanGanev 谢谢 - 我想添加新记录......不更新......所以每次插入都会添加一个新的 { "message_body" : "whatsup", "message_subject" : "whatsup", “message_date”:“20/01/2017”} 对象
  • 您希望将该对象添加到哪里?如果您将其添加到单独的集合中,例如“sent_messages”,那么您实际上是在插入一条记录(尽管我没有看到这样做的意义,因为您没有保留有关发送消息的用户的信息)。如果您将消息添加到现有用户记录,则您正在执行文档更新。
  • @TsvetanGanev 谢谢 - 明白了 - 看看我的解决方案 - 想知道你的想法
  • 是的,$push 应该可以解决问题。

标签: node.js mongodb


【解决方案1】:

知道了...需要使用 $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);
            }
        });
   }

};

【讨论】:

    猜你喜欢
    • 2011-12-03
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    • 2019-08-29
    • 1970-01-01
    相关资源
    最近更新 更多