是否可以仅显示整个更新记录而不是更新字段?

时间:2017-05-17 03:14:44

标签: node.js mongodb updates

基本上,我正在创建一个库存管理应用程序,并希望向用户显示更新的记录,不仅仅是已更新的字段,而是整个文档本身。我的问题是

*如何向用户显示整个更新记录而不是更新字段? *

我正在使用邮递员来测试这个API。这是我的代码,那些有评论的是我尝试过的。

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var url = 'mongodb://localhost:27017/myproject';

module.exports = {
/*getCollection : function(req, res){
    var issueQty = req.body.issueQty;
    var itemDescrip = req.body.itemDescrip;
    MongoClient.connect(url,function(err,db){
        assert.equal(null,err);
        var doc = findMultiple(db,req,function() {
            db.close();
        });
    });
        res.send(doc)
}*/
postCollection : function(req, res){
    var issueQty = req.body.issueQty;
    var itemDescrip = req.body.itemDescrip;
MongoClient.connect(url, function(err, db) {
    assert.equal(null, err);
    updateRecord(db, req, function() {
    db.close();
    });
    //findMultiple(db, req, function(){
    //db.close();
    //});
});
    res.send('Record Found. Now updating this document...' + itemDescrip + ' 
Record Updated. This is the new record with updated issueQty '
    + issueQty )
}
}
var updateRecord = function(db, req, callback) {
db.collection('documents').updateMany(
  { 'Item Description': req.body.itemDescrip},
  {
    $set: { 'Issued QTY': req.body.issueQty }
  }
  ,
  function(err, results) {
    console.log(results);
    console.log('Done');
    callback(); 
});
};
/*var findMultiple = function(db, req, callback){
 var issueQty = req.body.issueQty;
 var itemDescrip = req.body.itemDescrip;
 var cursor = db.collection('documents').find({'Issued QTY': issueQty, 'Item 
 Description': itemDescrip});
 cursor.each(function(err,doc){
     assert.equal(err,null);
     if(doc != err){
         console.log('Successfully queried');
         console.log(doc);
         return doc;
     } else {
        callback();
     }

 });
};*/

我已经尝试将另一个函数findMultiple用于获取数据并在响应中显示更新的记录但是它没有工作并考虑将我的查询api和更新api链接在一起但不确定如何去做。感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:0)

你需要:

  1. updateRecord()内,使用更新操作的results对象调用回调
  2. postCollection()内,传递给updateRecord()的回调可以访问results对象

  3. postCollection : function(req, res){
      var issueQty = req.body.issueQty;
      var itemDescrip = req.body.itemDescrip;
      MongoClient.connect(url, function(err, db) {
        assert.equal(null, err);
        updateRecord(db, req, function(results) {
        res.send('Document...') //Do what you want with results here
        db.close();
      });
    });
    
    var updateRecord = function(db, req, callback) {
      db.collection('documents').updateMany(
        {'Item Description': req.body.itemDescrip},
        {$set: { 'Issued QTY': req.body.issueQty }},
        function(err, results) {
          console.log(results);
          console.log('Done');
          callback(results); //pass results to the callback
        });
     };