【问题标题】:MongoDB Upserts Variable name as a key (Node.JS)MongoDB Upserts 变量名作为键(Node.JS)
【发布时间】:2016-09-12 17:40:41
【问题描述】:

Node.JS、MONGODB、不使用 Mongoose

我有一个要保存的文档。当我使用 UPSERT 时,它会这样构造数据:

{ "_id" : ObjectId("573a123f55e195b227e7a78d"),
       "document" : 
               [ {"name" : "SomeName" } ]
}

当我使用 INSERT 时,它会将其全部插入到根级别:

{ "_id" : ObjectId("573a123f55e195b227e7a78d"), "name" : "SomeName" }

这显然会导致很多不一致。我尝试过各种各样的事情。我尝试过各种方法,例如 findOneAndReplace、Update with Upsert、Replace、$setOnInsert。当涉及到 Upsert 时,这一切似乎都是一样的。

我曾尝试使用 document[0] 来访问数组的第一个块,但这会引发错误... 'Unexpected Token ['

我已经尝试了各种方法,并在各种文档中挖掘了几个小时,并在上下搜索过有此问题的其他人,但对于其他人来说,这似乎不是一个有据可查的问题。

任何人有什么建议可以确保所有字段都在 ROOT 级别,而不是嵌套在变量名下?相关代码如下。

findReplace: function(db, document, collection) {

    var dbCollection = db.collection(collection);

    var filter = document.name;

    return new Promise(function(resolve, reject) {
        dbCollection.updateOne({
            "name" : filter
        }, { 
            document
        }, {
            upsert: true
        }, function(err, result) {
            if (err) {
                console.log('error', err)
                reject(err);
            }
            console.log("Found Document and Upserted replacement Document");
            resolve([{'status' : 'success'}]);
        });
    });
}

【问题讨论】:

    标签: node.js mongodb variables key


    【解决方案1】:

    当你这样做时:

    { 
       document
    }
    

    您正在创建一个包含document 属性和变量值作为其值的对象:

    { 
       document: [ {"name" : "SomeName" } ]
    }
    

    This is new functionality from ES6。如果要访问文档变量的第一项,请不要创建新对象:

    return new Promise(function(resolve, reject) {
        dbCollection.updateOne({
            "name" : filter
        }, document[0], { // <========
            upsert: true
        }, function(err, result) {
            if (err) {
                console.log('error', err)
                reject(err);
            }
            console.log("Found Document and Upserted replacement Document");
            resolve([{'status' : 'success'}]);
        });
    });
    

    【讨论】:

    • 完美,谢谢!我一直在努力跟上 ES6 的变化,但总是有新的东西。总是小事。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-11
    • 2011-12-30
    • 2019-12-01
    • 2015-10-23
    • 1970-01-01
    相关资源
    最近更新 更多