mongodb - 将对象插入 Mongoose 中的数组模式

标签 mongodb mongoose

我有这个 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
});

并尝试通过这样做来更新模型:

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 修饰符应用于非数组

有什么想法吗?

最佳答案

mongoose 在一次操作中为您完成这项工作。

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

请记住,使用此方法,您将无法使用架构的“pre”功能。

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

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

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

关于mongodb - 将对象插入 Mongoose 中的数组模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15621970/

相关文章:

node.js - mongoose中的位置,mongoDB

node.js - 如何在 Mongoose 中查询嵌套数组

node.js - MongoDB/Mongoose - 用逗号导入数字

node.js - 记录 mongodb 中的所有请求

javascript - 回调不是 mongoose.find({}) 中的函数

node.js - "Argument must be a string"在 Node.js 中具有某些 MongoDB ObjectID

asp.net-mvc - 如何用MongoDB实现关键字和位置搜索?

mongodb - 我应该如何配置我的 Mongodb 集群?

mongodb - 关于 Redux 中的规范化

node.js - Actor 错误: Cast to ObjectId failed for value "route-name" at path "_id" for model