如果 tmx 较新,我的应用程序应该更新,如果较旧,则不执行任何操作,如果不存在,则插入文档。 如果插入文档,则它可以正常工作,否则它无法正确更新或显示 E11000 dup key。 试图弄清楚我的回调是否错误或逻辑错误。 (我是node.js+mongodb的新手)MongoClient = require('mongodb').MongoClient, 断言 = require('断言'), url = 'mongodb://localhost:27017/pfc';
MongoClient.connect(url, function (err, db) {
run(db);
});
function run(db) {
fs.readFile('log.log', 'utf8', function (err, source) {
if (err) throw err;
var dataFile = JSON.parse(source);
dataFile.forEach(function (item) {
upsert(db, item, function (err, result) {
if (err) console.dir(err);
});
});
})
}
function upsert(db, doc, callback) {
db.collection('flags').findOne({vid: doc.vid}, function (err, item, result) {
if (item.vid != null) {
if (!(item.tmx instanceof Date)) {
item.tmx = new Date(item.tmx)
}
if(!(doc.tmx instanceof Date)){
doc.tmx = new Date(doc.tmx)
}
if (item.tmx < doc.tmx) {
console.dir("Date validation")
db.collection('flags').updateOne({vid: item.vid}, {
$set: {
"tmx": doc.tmx
}
},{upsert:true}, function (err, result) {
callback(err, result);
}
)
callback(err, result);
}
else{
console.dir("older")
callback(err, result);
}
}
else {
db.collection('flags').insertOne(doc, function(err, result) {
callback(err, result);
});
}
})}
编辑: “log.log”文件中的文档具有以下结构:
{ 视频:2848 TMX:“2015-07-18T23:56:17.000Z” }
{ 视频:2848 tmx: 2015-07-19T00:00:17.000Z }
collection.find({vid: doc.vid},function(err,item){
if(!item)//在集合中未找到 vid: 2848 的项目 将文档插入集合 else if(item)//找到一个 vid:2848 的项目 if (item.tmx < doc.tmx)//仅当 doc.tmx 较新时更新 使用最新文档更新集合
在@Aaron Dufour的帮助下我摆脱了回调问题,谢谢:) 但现在的问题是,当我已经填充了集合并在 log.log 中查找最新文档时,它从最旧的文档开始,直到再次最新:(
最佳答案
您的 upsert
容易受到竞争条件的影响,并且 run
并行调用它很多次,因此这可能就是问题所在。目前尚不清楚 doc
到底是什么样子,因此您可能需要稍微复杂一点的逻辑,但这里有一个使用 Mongo 的 upsert
的版本,使事情变得更安全:
function upsert(db, doc, callback) {
db.collection('flags').update({vid: doc.vid}, {$set: doc}, {upsert: true}, function(err) {
db.collection('flags').update({vid: doc.vid, tmx: {$lt: doc.tmx}}, {$set: tmx: doc.tmx}, function(err) {
callback();
});
});
}
关于javascript - Node.js Mongodb 回调问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31900116/