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

查看:17
本文介绍了将对象推入 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 为您完成一个操作.

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

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

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"可选参数.否则,您将获得旧文档退还给您.因此,猫鼬版本 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天全站免登陆