How to update a mixed type field in Mongoose without overwriting the current data?

I have the following diagram

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);

The "name" field is multilingual. I mean, I will store multilingual data like

name: {
    "en": "My Shop",
    "es": "Mi Tienda"
}

My problem is that in the controller I use this code to update the store:

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);
    });
};

and obviously, new data is redefining old data. I need to renew old data with new.

Is there any way to do this?

+4
source share
2 answers

You should use the .markModified () method. See Document http://mongoosejs.com/docs/schematypes.html#mixed

, , Mongoose . "" Mongoose, , .markModified() , , .

person.anything = { x: [3, 4, { y: "changed" }] };
person.markModified('anything');
person.save(); // anything will now get saved
+11

"dot notation" :

Shop.findByIdAndUpdate(req.params.shopid, {
    "$set": {
        "name.en": req.body.name
    }
}, function(err, shop) {
    if (err) return res.json(err);
        res.json(shop);
    });
});

"en", , , "" , . , "de", , "de" .

+9

All Articles