gpt4 book ai didi

node.js - mongodb-collection 中的单个对象 [v 3.0.2]

转载 作者:太空宇宙 更新时间:2023-11-04 02:53:21 24 4
gpt4 key购买 nike

我想要一个仅包含一个元素的集合(测试)。因此,我将更新查询设置为空对象:

db.test.find() -> empty
var mongoData = {"name": "Biff"};
db.test.update({}, mongoData, {upsert:true}, cb);
db.test.find() -> {"name": "Biff", "_id":"1"}

var mongoData = {"name": "Buff"};
db.test.update({}, mongoData, {upsert:true}, cb);
db.test.find() -> {"name": "Buff", "_id":"1"}

为什么不是这个:

db.test.find() -> empty
var mongoData = {"name": "Biff"};
db.test.update({}, mongoData, {upsert:true}, cb);
db.test.find() -> {"name": "Biff", "_id":"1"}

var mongoData = {"name": "Buff"};
db.test.update({}, mongoData, {upsert:true}, cb);
db.test.find() -> [{"name": "Biff", "_id":"1"}, {"name": "Buff", "_id":"2"}]

更新空对象“{}”似乎可以确保在此集合中不会创建另一个元素。我想,找不到 {},因此创建了 {"name":"Biff"} 并为其设置了 _id。如果我再次尝试更新 {},它不会使用不同的 _id 再次创建 {"name":"Biff"}。它正在覆盖集合中的唯一元素。为什么会这样?

最佳答案

我对此称为错误:

这里是证明这一点的代码 list ,如果您自己的代码不同,那么这应该是一个指南:

var async = require('async'),
mongodb = require('mongodb'),
MongoClient = mongodb.MongoClient;

MongoClient.connect('mongodb://localhost/test',function(err,db) {
if (err) throw err;

var collection = db.collection('bifftest');

async.eachSeries(
["Biff","Buff"],
function(name,callback) {
collection.update({},{ "name": name },{ "upsert": true },callback);
},
function(err) {
if (err) throw err;

collection.find({}).toArray(function(err,results) {
if (err) throw err;
console.log(results);
});
}
);
});

返回:

[ { _id: 55b8992dcc8638610dca2e7c, name: 'Buff' } ]

正如预期的那样。

关于node.js - mongodb-collection 中的单个对象 [v 3.0.2],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31695791/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com