将对象推入Mongoose中的数组架构 [英] pushing object into array schema in Mongoose

查看:65
本文介绍了将对象推入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
});

,然后尝试通过以下方式更新模型:

and trying to update the model by doing this:

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

    });
  });

我不是在声明messages接受对象数组吗?
错误: MongoError:无法将$ push/$ pushAll修饰符应用于非数组

I'm I not declaring the messages to take an array of objects?
ERROR: MongoError: Cannot apply $push/$pushAll modifier to non-array

有什么想法吗?

推荐答案

猫鼬一次完成此操作即可.

mongoose does this for you in one operation.

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

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

Please keep in mind that using this method, you will not be able to make use of the schema's "pre" functions.

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

从最新的mogoose开始,findbyidandupdate需要添加一个"new:true"可选参数.否则,您将得到旧文档给您.因此,Mongoose版本4.x.x的更新转换为:

As of the latest mogoose findbyidandupdate needs to have a "new : true" optional param added to it. Otherwise you will get the old doc returned to you. Hence the update for Mongoose Version 4.x.x converts to :

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

这篇关于将对象推入Mongoose中的数组架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆