如果给定的 _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 中发生?
或
建议另一种解决方案来确定集合中的文档是否已更新或插入?
谢谢你
最佳答案
结果是一个包含其自身属性“result”的结构,该属性具有子属性。因此,您需要在正确的级别进行检查:
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”的值,“modified”从数据实际改变开始计算。
关于javascript - Nodejs、MongoDB - 确定集合中的文档是否已更新或插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31400794/