【发布时间】: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