Mongodb dot field update

走远了吗. 提交于 2019-12-06 14:58:37

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.

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