【问题标题】:PUT method in Node.js/MongoDBNode.js/MongoDB 中的 PUT 方法
【发布时间】:2015-11-18 17:04:37
【问题描述】:

我在使用 Node.js (MongoDB collection.update) 中的简单 PUT 方法时遇到问题。任何帮助,将不胜感激。在这一点上,我没有收到错误,只是一个空响应。

index.js:

app.put('/UpdateValues/:collection/:entity', function(req, res) {
   var params = req.params;
   var entity = params.entity;
   var collection = params.collection;

   var value1 = req.body.value1;
   var value2 = req.body.value2;

   if (entity) {
       collectionDriver.updateValues(collection, entity, value1, value2, function(error, objs) {
          if (error) { res.status(400).send(error); }
          else { res.status(200).send(objs); }
       });
   } else {
      res.send(400, {error: 'bad url', url: req.url});
   }
});

collectionDriver.js:

CollectionDriver.prototype.updateValues = function(collectionName, nameDoc, value1new, value2new, callback) { 
    this.getCollection(collectionName, function(error, the_collection) {
        if (error) callback(error);
        else {

            the_collection.update(
               { name: nameDoc },
               { $set: {
                   value1: value1new,
                   value2: value2new
                }},
                function( err, result ) {
                        if ( err ) throw err;
                    }
                );

        }
    });
};

测试:

$ curl -i -X PUT -H 'Content-Type: application/json' -d '{"value1":"1","value2":"1"}' http://localhost/UpdateValues/collection/test

【问题讨论】:

  • 您传入的callback 永远不会在成功时被引用。 .update() 也不会返回修改后的文档。如果您期望修改后的响应,您可能需要.findOneAndUpdate()
  • 感谢布雷克斯!值正在更新,只是没有发生回调。

标签: node.js mongodb rest put


【解决方案1】:

引用您在函数中传入的回调。目前你没有。您似乎也正在响应修改后的文档,因此您需要.findOneAndUpdate()

CollectionDriver.prototype.updateValues = function(collectionName, nameDoc, value1new, value2new, callback) { 
  this.getCollection(collectionName, function(error, the_collection) {
    if (error) callback(error);

    the_collection.findOneAndUpdate(    // <-- new method
      { name: nameDoc },
      { $set: {
        value1: value1new,
        value2: value2new
      }},
      { returnOriginal: false },        // <-- tells to return modified document
      callback                          // <--- passes to callback you passed in
    );

  });
});

【讨论】:

    猜你喜欢
    • 2014-06-27
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 2019-07-18
    相关资源
    最近更新 更多