我有以下架构
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ShopSchema = new Schema({
name: Schema.Types.Mixed,
country: {
type: String,
default: ''
},
createdAt: {
type: Date,
default: Date.now
},
defaultLanguage: {
type: String
},
account: {type : Schema.ObjectId, ref : 'Account'},
});
mongoose.model('Shop', ShopSchema);
“名称”字段是多语言的。我的意思是,我会保留多语言数据,例如
name: {
"en": "My Shop",
"es": "Mi Tienda"
}
我的问题是,在 Controller 中,我正在使用此代码来更新商店:
var mongoose = require('mongoose')
var Shop = mongoose.model('Shop')
exports.update = function(req, res) {
Shop.findByIdAndUpdate(req.params.shopid, {
$set: {
name: req.body.name
}
}, function(err, shop) {
if (err) return res.json(err);
res.json(shop);
});
};
很明显,新数据会覆盖旧数据。我需要的是用新数据扩展旧数据。
有什么方法可以做到吗?
最佳答案
你应该使用方法.markModified()。请参阅文档 http://mongoosejs.com/docs/schematypes.html#mixed
Since it is a schema-less type, you can change the value to anything else you like, but Mongoose loses the ability to auto detect and save those changes. To "tell" Mongoose that the value of a Mixed type has changed, call the .markModified(path) method of the document passing the path to the Mixed type you just changed.
person.anything = { x: [3, 4, { y: "changed" }] };
person.markModified('anything');
person.save(); // anything will now get saved
关于node.js - 如何在不覆盖当前数据的情况下更新 Mongoose 中的混合类型字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31154258/