node.js - 如何在不覆盖当前数据的情况下更新 Mongoose 中的混合类型字段?

标签 node.js mongodb mongoose mongodb-query

我有以下架构

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/

相关文章:

mongodb - 全文检索 MongoDB/Mongoengine

javascript - 在 JavaScript 中读取数组

node.js - Nodejs promise 类型错误 : Cannot read property 'then' of undefined

validation - 验证多个 Mongoose 模式属性?

javascript - 从 blob 在 nodeJs 中创建图像文件

node.js - 如何使用 Parse Server 登录/注册用户?

node.js - Heroku "npm install jugglingdb mongoose"已经做了

node.js - 如何重置环回内存 DB

performance - 如何在 ycsb 中的加载生成阶段之后验证数据已加载到 mongodb 中?

mongodb - 修复 mongodb 时出错