mongodb 将对象推入 Mongoose 中的数组模式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15621970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pushing object into array schema in Mongoose
提问by user1460015
I have this mongoose schema
我有这个猫鼬模式
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);
});
});
I'm I not declaring the messages
to take an array of objects?
ERROR:MongoError: Cannot apply $push/$pushAll modifier to non-array
我不是声明messages
要获取一组对象吗?
错误:MongoError:无法将 $push/$pushAll 修饰符应用于非数组
Any ideas?
有任何想法吗?
回答by fino
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
http://mongoosejs.com/docs/middleware.html
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 :
截至最新的 mogoose findbyidandupdate 需要添加一个“new : true”可选参数。否则,您将把旧文件退还给您。因此,Mongoose 4.xx 版的更新转换为:
Contact.findByIdAndUpdate(
info._id,
{$push: {"messages": {title: title, msg: msg}}},
{safe: true, upsert: true, new : true},
function(err, model) {
console.log(err);
}
);