我有这个 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/