【发布时间】:2015-11-01 05:16:39
【问题描述】:
如果 tmx 较新,则我的应用程序应该更新,如果较旧则什么也不做,如果不存在则插入文档。 如果文档被插入,它可以正常工作,否则它不能正确更新或显示 E11000 dup key。 试图弄清楚我的回调是错误的还是逻辑错误。 (我是 node.js+mongodb 的新手) MongoClient = require('mongodb').MongoClient, 断言 = 要求('断言'), 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
在@Aaron Dufour 的帮助下,我摆脱了回调问题,谢谢 :) 但是现在的问题是,当我已经填充了集合并在 log.log 中查找最新文档时,它会从最旧的文档开始直到最新的文档:(
【问题讨论】:
-
您的 upsert 逻辑容易受到竞争条件的影响,这可能会导致问题。你试过 Mongo 的内置 upsert 吗?
-
当我必须比较要更新的日期时,看不到如何使用它
-
因为如果项目不存在,我会得到 item.tmx 属性为空错误,所以我需要确认项目存在,以便我可以将文件中的日期与 mongodb 中的日期进行比较跨度>
-
您是否有多个具有相同
vid值的文档? -
是的,我有。该文件现在有超过 60000 个文档,我平均有 40 个具有相同 vid 的文档
标签: javascript node.js mongodb