我有这个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
});
Run Code Online (Sandbox Code Playgroud)
并尝试通过执行以下操作来更新模型:
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);
});
});
Run Code Online (Sandbox Code Playgroud)
我不是要宣布messages采取一系列物体?
错误: MongoError:无法将$ push/$ pushAll修饰符应用于非数组
有任何想法吗?
fin*_*ino 111
mongoose在一次手术中为你做这件事.
Contact.findByIdAndUpdate(
info._id,
{$push: {"messages": {title: title, msg: msg}}},
{safe: true, upsert: true},
function(err, model) {
console.log(err);
}
);
Run Code Online (Sandbox Code Playgroud)
请记住,使用此方法,您将无法使用架构的"预"功能.
http://mongoosejs.com/docs/middleware.html
截至最新的mogoose,findbyidandupdate需要添加一个"new:true"可选参数.否则,您将获得返回给您的旧文档.因此,Mongoose Version 4.xx的更新转换为:
Contact.findByIdAndUpdate(
info._id,
{$push: {"messages": {title: title, msg: msg}}},
{safe: true, upsert: true, new : true},
function(err, model) {
console.log(err);
}
);
Run Code Online (Sandbox Code Playgroud)
有两种方法可以将数据推送到数组中
第一种方式:
let newMessage = {title: "new title", msg: "new Message"}
let result = await Contact.findById(id);
result.messages.push(newMessage);
await result.save();
Run Code Online (Sandbox Code Playgroud)
第二种方式
let result = await Contact.findByIdAndUpdate(
id,
{$push: {"messages": {title: title, msg: msg}}},
{upsert: true, new : true})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
81172 次 |
| 最近记录: |