Nodejs和MongoDB:无法从函数返回值

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; } 

使用上面的代码,我不能够返回doc.value.seq的值。 当做console.log(obj.getNextSequence)它打印undefined

我想要函数返回doc.value.seq的值。

我不熟悉mongoskin,所以我并不积极,这是正确的,但数据库查询通常是asynchronous的,所以你需要通过callback访问查询的值。

我猜你的“getNextSequence”函数在数据库查询完成之前(即在“temp = doc.value.seq”语句之前)返回“temp”variables。

尝试这样的事情:

 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的callback中访问“temp”。

findAndModify是一个asynchronous函数。 你的console.log行会你返回temp 之后运行,因此这个行是undefined 。 为了得到这个工作,你需要使用你自己的asynchronous方法。 在你的情况下有两种可用的方法。

callback :

你已经使用了一个callback,你提供了作为findAndModify的最后一个参数。 您可以扩展这种方法,并将其作为您自己的callback,如下所示:

 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); } ); } 

当然,这将需要您将callback传递给getNextSequence并遵循上游的callback模式。 你也可能想要处理来自mongoskin的错误,并做一些自己的处理。

承诺 :

如果你没有提供findAndModify的callbackfindAndModify ,它会返回一个你可以链接到的promise,如下所示:

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

再一次,这将要求你遵循上游的承诺模式。 如果您select这种方法,您将需要阅读诺言,以便您可以正确处理错误,这在上面的例子中我没有提到。