如果给定的_id不存在,我用{upsert:true}调用mongoDB更新函数来插入新文档。我想确定文件是否已插入或更新。就像这个问题我发现使用java但只使用Nodejs。
how to check if an document is updated or inserted in MongoDB
这是我的数据库电话。
app.post('/mongoSubmit', function(req, res) {
console.log("This is the req.body" + JSON.stringify(req.body, null, 4));
var updateCustomer = function(db, callback){
db.collection('customers1').update(
{_id:req.body.email},
{ first: req.body.firstName,
last: req.body.lastName,
phone: req.body.phone,
email: req.body.email,
subjectIndex: req.body.subject,
messageIndex: req.body.message
},
{ upsert: true},
function(err, result){
if(err){console.log("database error" + err)}
callback(result);
}
);
}
MongoClient.connect(url, function(err, db){
updateCustomer(db, function(result){
console.log("these are the results" + JSON.stringify(result, null, 4));
/*
** Return Either
*
these are the results{
"ok": 1,
"nModified": 0,
"n": 1,
"upserted": [
{
"index": 0,
"_id": "sjr6asdfsadfsadf28@gmail.com"
}
]
}
/*
*
* or
these are the results{
"ok": 1,
"nModified": 1,
"n": 1
}
//BUT *************** Problem using this Value *********************
console.log("this is the value of Modified" + result.nModified);
/*
** Returns undefined
*/
if(result.nModified == 1){
console.log("Updated document");
}
else{
console.log("Inserted document");
}
db.close();
res.render('applications', {
title:"Title"
});
});
});
});
我也尝试过做测试
if(result.hasOwnProperty('upserted'){
//log an Insert
if(result.upserted == true {
//log an Insert
if(result.nModified == 1){
// log an update
if(result.nModified == true){
//log an update
并且还将upserted作为参数添加到我从其他论坛找到的回调中。
function(err, result, upserted){
//callback function
//upserted was undefined
})
我的结果令人困惑。我如何使用属性值记录对象,但是当我尝试记录该特定属性时,它是否未定义?
有人可以解释为什么这可能会在javascript中发生吗?
或
建议另一个解决方案,以确定集合中的文档是否已更新或插入?
谢谢
答案 0 :(得分:3)
结果是一个结构,它包含了它自己的属性"结果"它具有子属性。因此,您需要在适当的级别进行检查:
var async = require('async'),
mongodb = require('mongodb'),
MongoClient = mongodb.MongoClient;
MongoClient.connect('mongodb://localhost/test',function(err,db) {
db.collection('uptest').update(
{ "a": 1 },
{ "$set": { "b": 2 } },
{ "upsert": true },
function(err,result) {
if (err) throw err;
if (result.result.hasOwnProperty('upserted') ) {
console.log( JSON.stringify( result.result.upserted, undefined, 2 ) );
}
console.log( "matched: %d, modified: %d",
result.result.n,
result.result.nModified
);
}
);
});
首次运行时,您将获得"数组" " upserted"像这样:
[
{
"index": 0,
"_id": "55a4c3cfbe78f212535e2f6a"
}
]
matched: 1, modified: 0
在第二次运行时使用相同的值,然后不添加或修改任何内容:
matched: 1, modified: 0
更改" b"的值和#34;修改"自数据实际改变以来计算。