简体   繁体   English

如何将mongodb数据库查询记录到控制台(不是mongo shell)?

[英]How do I log a mongodb database query to the console (not the mongo shell)?

I would like to console.log() the results of a mongodb database query without going into the mongo shell. 我想在不进入mongo shell的情况下console.log()mongodb数据库查询的结果。 Below is my code. 下面是我的代码。 The relevant parts are in bold. 相关部分以粗体显示。

router.put('/quotes/:id', (req, res, next) => {
  let personToUpdate = req.params.id;
  **console.log("old name: " + JSON.stringify(db.collection("quotes").findOne({ _id: ObjectId(personToUpdate) })) );**
  db.collection("quotes").findOneAndUpdate( 
    { _id: ObjectId(personToUpdate)},
    {$set: {
      name: req.body.name
      }
    }, function (err, object) {
      if (err) {
        console.warn(err.message);
      } else {
        **console.log("new name: " + req.body.name);**
      }
    }
  );
});

I have tried: 我努力了:

console.dir(), but that returns [object, object]. console.dir(),但是返回[object,object]。 I have tried print() and printjson(), but those are mongo shell exclusive commands. 我已经尝试过print()和printjson(),但是它们是mongo shell独占命令。

The end result should be that when the user changes a name through a put request, first it logs the old name that is stored in the database to the console, then at the end of the findOneAndUpdate() mongodb command to change the name, it logs the new name that the user submitted through req.body.name 最终结果应该是,当用户通过放置请求更改名称时,首先它将存储在数据库中的旧名称记录到控制台,然后在findOneAndUpdate()mongodb命令的末尾更改名称,它将记录用户通过req.body.name提交的新名称

findOne is async, so you'd need to provide a callback to get the result and then put the rest of your code within that callback so that the update doesn't occur until after you've got the original document. findOne是异步的,因此您需要提供一个回调以获取结果,然后将其余代码放入该回调中,以便直到获得原始文档后才进行更新。

However, the original document is passed to the findOneAndUpdate callback by default, so you can eliminate the findOne call and get the original name from there. 但是,默认情况下findOneAndUpdate原始文档传递给findOneAndUpdate回调,因此您可以消除findOne调用,并从那里获取原始名称。

router.put('/quotes/:id', (req, res, next) => {
  let personToUpdate = req.params.id;
  db.collection("quotes").findOneAndUpdate( 
    { _id: ObjectId(personToUpdate)},
    {$set: {
      name: req.body.name
      }
    }, function (err, result) {
      if (err) {
        console.warn(err.message);
      } else {
        console.log("old name: " + result.value.name);
        console.log("new name: " + req.body.name);
      }
    }
  );
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM