MongoDB 将变量名称更新为键 (Node.JS)

MongoDB Upserts Variable name as a key (Node.JS)

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

当你这样做时:

{ 
   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'}]);
    });
});