Толкание объекта в схему массива в 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 для не-массива
Любые идеи?
Ответы
Ответ 1
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 Version 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);
}
);