javascript - Nodejs、MongoDB - 确定集合中的文档是否已更新或插入

标签 javascript node.js mongodb

如果给定的 _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/

相关文章:

node.js - $eq 不适用于 $unwind 结果 mongoose

javascript - 如何将 GET api 写入 Node.js 中的现有文件中

MongoDB:基于另一个集合从一个集合中进行条件选择

mongodb - 从 blob 转换为二进制以将其保存到 mongodb

javascript - 如何使用 javascript css 或 html attr 禁用 iOS 链接预览

javascript - 更改plotly js中的z索引标签

node.js - 使用 mongoose find 查询获取数据时获取未指定的数据

mongodb - 如何在不使用封顶集合的情况下在MongoDB中存储一组有序文档

javascript - RGBA 不透明度重置 (Etch-A-Sketch)

javascript - Array.prototype.find() 未定义