2017-09-02 123 views
2
var config = require('config.json'); 
var mongo = require('mongoskin'); 
var db = mongo.db(config.connectionString, { native_parser: true }); 

module.exports.getNextSequence = function (name) { 
    var temp; 
    db.collection("counters").findAndModify(
     { _id: name },   // query 
     [],      // represents a sort order if multiple matches 
     { $inc: { seq: 1 } }, // update statement 
     { new: true },   // options - new to return the modified document 
     function (err, doc) { 
      temp = doc.value.seq; 
      console.log(temp); // <-- here the temp is getting printed correctly 
     } 
    ); 
    return temp; 
} 

使用上面的代碼返回值,我無法返回的​​值。在執行console.log(obj.getNextSequence)時,它會打印undefined的NodeJS和MongoDB:無法從功能

我想函數返回值​​。

回答

1

我對mongoskin不熟悉,所以我並不積極,這是正確的,但數據庫查詢通常是異步的,所以您需要通過回調訪問查詢的值。

我猜你的「getNextSequence」函數在數據庫查詢完成之前(即在「temp = doc.value.seq」語句之前)返回「temp」變量。

嘗試是這樣的:

module.exports.getNextSequence = function (name, callback) { 
    var temp; 
    db.collection("counters").findAndModify(
     { _id: name },   // query 
     [],      // represents a sort order if multiple matches 
     { $inc: { seq: 1 } }, // update statement 
     { new: true },   // options - new to return the modified document 
     function (err, doc) { 
      temp = doc.value.seq; 
      callback(temp); 
     } 
    ); 
} 

然後從傳遞給getNextSequence回調中訪問 「溫度」。

1

findAndModify異步函數。您的console.log行將在之後運行,您將返回temp,因此將爲undefined。爲了得到這個工作,你需要使用你自己的異步方法。在你的情況下有兩種可用的方法。

Callbacks

您已經在使用一個回調,您所提供的最後一個參數findAndModify。你可以擴展這一做法,並反饋到你自己的回調這一點,如下所示:

module.exports.getNextSequence = function (name, callback) { 
    db.collection("counters").findAndModify(
     { _id: name }, 
     [], 
     { $inc: { seq: 1 } }, 
     { new: true }, 
     function (err, doc) { 
      if (err) { 
       return callback(err); 
      } 

      callback(null, doc.value.seq); 
     } 
    ); 
} 

當然,這需要你的回調傳遞到getNextSequence,並按照上游回調格局。您也可能想要處理來自mongoskin的錯誤,並對自己的操作進行一些處理。

Promises

如果不提供回調findAndModify,它會返回一個承諾,你可以鏈上,如下所示:

module.exports.getNextSequence = function (name) { 
    return db.collection("counters").findAndModify(
     { _id: name }, 
     [], 
     { $inc: { seq: 1 } }, 
     { new: true } 
    ).then(function (doc) { 
     return doc.value.seq; 
    }); 
} 

同樣,這需要你遵循上游的承諾模式。如果您選擇這種方法,您需要閱讀承諾,以便您可以正確處理錯誤,這在上面的示例中我沒有提到。