Mongodb dot field update

亡梦爱人 提交于 2019-12-08 04:26:20

问题


I have the following Schema in Mongo:

var OrderSchema = new Schema({
    postcode: String,
    ...
    status: {
        last_check: { type: Date },
        date: Date,
        code: String,
        postnum: String,
        text: String,
        class: String
    },
});

I have a function to save a data (old way is commented):

function save_order(data) {
//    var order = new Order(data);
//    var upsertData = order.toObject();
//    delete upsertData._id;
//    Order.findOneAndUpdate({postcode: order.postcode}, upsertData, {upsert: true}, function (err) {
  Order.update({postcode: data.postcode}, {$set:data}, function (err) {
    if (err) console.log('err');
  });
}

Here data example passed to a function:

{ postcode: 'BV123456789BY',
  status: 
   { last_check: 1413539153572,
     code: '06',
     postnum: '247431',
     date: Thu Oct 16 2014 09:52:00 GMT+0300 (Восточная Европа (лето)),
     text: '06. Поступило в участок обработки почты (247431) Светлогорск - 1' } }

Function to set status.class works fine - it does not overwrite status :

function setByOrderId(id, data) {
//   data = {'status.class': 'danger'}
    Order.update({_id: id}, {$set: data}, function (err) {
        if (err) console.log('err');
    });
}

Problem is that when I update the status, the value of status.class disappears... How should I update the status without overwriting status.code? Thank you.


回答1:


Of course it does since this is exactly what you are asking it to do. Despite your title, there is no use of "dot notation" here at all. This is of course what you want to do if you intend to not overwrite existing properties. Right now you are just replacing the entire object, despite your use of $set where unless you change the structure here is basically redundant.

To "fix" this, you need to manipulate your data object first. With something along these lines:

var newobj = {};
Object.keys( data ).forEach(function(key) {
    if ( typeof(data[key]) == "object" ) {
       Object.keys( data[key] ).forEach(function(subkey) {
           newobj[key + "." + subkey] = data[key][subkey];
       });
    } else {
       newobj[key] = data[key];
    }
});

That gives you and output in the newobj structure like this:

{
    "postcode" : "BV123456789BY",
    "status.last_check" : 1413539153572,
    "status.code" : "06",
    "status.postnum" : "247431",
    "status.date" : ISODate("2014-10-17T11:28:20.540Z"),
    "status.text" : "06. Поступило в участок обработки почты (247431) Светлогорск - 1"
}

Then of course you can proceed with your normal update and get everything right:

Order.update({ "postcode": newobj.postcode}, { "$set": newobj }, function (err) {
    if (err) console.log(err);
});

Of course you would need some recursion for a more nested structure, but this should give you the general idea. Dot notation is the way to go, but you need to actually use it.



来源:https://stackoverflow.com/questions/26422929/mongodb-dot-field-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!