簡體   English   中英

從未調用過Node.js MongoDB collection.update()回調

[英]Node.js MongoDB collection.update() callback never called

誰能解釋為什么下面的回調從未得到調用?

從未調用過由回調執行的更新。 我錯過了什么 ?

collection.update({_id:partner._id}, 
                    {$set: {
                            groups: newGroups
                          }
                    },
                    { upsert: false, w: 1 },
                    function(err, status){
                      console.log("update callback ");
                      if (err){
                        console.log("Error updating "+err.message);
                        callback(false);
                      } else {
                        console.log("Record updated as "+JSON.stringify(status));
                        callback(true);
                      }
                    }
  );

您可以將其包裝在帶有回調作為參數的函數中:

    //Except for callback as a parameter, every parameter is not compulsory
    function yourFunctionName(id, newGroups, callback) {
      collection.update({
          _id: partner._id
        }, {
          $set: {
            groups: newGroups
          }
        }, {
          upsert: false,
          w: 1
        },
        function(err, status) {
          console.log("update callback ");
          if (err) {
            console.log("Error updating " + err.message);
            callback(false);
          } else {
            console.log("Record updated as " + JSON.stringify(status));
            callback(true);
          }
        }
      )
    }

然后像這樣調用函數:

yourFunctionName(params, function(result) {
  //Do anything with the result
});

如果您想了解回調函數的工作原理, 可能會對您有所幫助。

例如在node(sailsJs)中

Model.update({id:'xxxxxxxxxxxxxxxx'},{name:'Flynn'}).exec(function afterwards(err, updated){

if (err) {
//handle error here!
return;
}

console.log('Updated user to have name ' +    updated[0].name);
 });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM