将对象推送到Mongoose中的数组模式

use*_*015 50 mongoose mongodb

我有这个mongoose架构

var mongoose = require('mongoose');

var ContactSchema = module.exports = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  phone: {
    type: Number,
    required: true,
    index: {unique: true}
  },
  messages: [
  {
    title: {type: String, required: true},
    msg: {type: String, required: true}
  }]
}, {
    collection: 'contacts',
    safe: true
});
Run Code Online (Sandbox Code Playgroud)

并尝试通过执行以下操作来更新模型:

Contact.findById(id, function(err, info) {
    if (err) return res.send("contact create error: " + err);

    // add the message to the contacts messages
    Contact.update({_id: info._id}, {$push: {"messages": {title: title, msg: msg}}}, function(err, numAffected, rawResponse) {
      if (err) return res.send("contact addMsg error: " + err);
      console.log('The number of updated documents was %d', numAffected);
      console.log('The raw response from Mongo was ', rawResponse);

    });
  });
Run Code Online (Sandbox Code Playgroud)

我不是要宣布messages采取一系列物体?
错误: MongoError:无法将$ push/$ pushAll修饰符应用于非数组

有任何想法吗?

fin*_*ino 111

mongoose在一次手术中为你做这件事.

Contact.findByIdAndUpdate(
    info._id,
    {$push: {"messages": {title: title, msg: msg}}},
    {safe: true, upsert: true},
    function(err, model) {
        console.log(err);
    }
);
Run Code Online (Sandbox Code Playgroud)

请记住,使用此方法,您将无法使用架构的"预"功能.

http://mongoosejs.com/docs/middleware.html

截至最新的mogoose,findbyidandupdate需要添加一个"new:true"可选参数.否则,您将获得返回给您的旧文档.因此,Mongoose Version 4.xx的更新转换为:

Contact.findByIdAndUpdate(
        info._id,
        {$push: {"messages": {title: title, msg: msg}}},
        {safe: true, upsert: true, new : true},
        function(err, model) {
            console.log(err);
        }
    );
Run Code Online (Sandbox Code Playgroud)

  • "new" - 以便您获得更新的文档作为回报(阅读答案说明)"upsert" - 可选.如果设置为true,则在没有文档与查询条件匹配时创建新文档.默认值为false,如果未找到匹配项,则不会插入新文档.http://docs.mongodb.org/manual/reference/method/db.collection.update/"safe" - http://stackoverflow.com/questions/4974686/mongodb-should-i-always-use-the-安全选项上,更新 (5认同)
  • 为什么`upsert`在这里? (3认同)
  • 这个答案对我帮助很大.但是那些选项有什么选择,`safe`,`upsert`和`new`? (3认同)
  • 谢谢你真正的答案:) (2认同)

Moh*_*adi 8

有两种方法可以将数据推送到数组中

第一种方式:

let newMessage = {title: "new title", msg: "new Message"}
let result = await Contact.findById(id);
result.messages.push(newMessage);
await result.save();
Run Code Online (Sandbox Code Playgroud)

第二种方式

let result = await Contact.findByIdAndUpdate(
        id,
        {$push: {"messages": {title: title, msg: msg}}},
        {upsert: true, new : true})
Run Code Online (Sandbox Code Playgroud)