【发布时间】:2015-10-02 17:54:17
【问题描述】:
如果给定的 _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 中会发生这种情况?
或
建议另一种解决方案来确定集合中的文档是否已更新或插入?
谢谢你
【问题讨论】:
标签: javascript node.js mongodb