3

我正在将 Mongoose 与 Bluebird 一起使用,并且在使用包含时间戳排序的查询时遇到错误。我正在尝试仅检索最新条目。该查询在使用内置 Promises 时有效。

有任何想法吗?谢谢!

var Promise        = require("bluebird"),    
    mongoose       = require('mongoose');

var Item = Promise.promisifyAll(mongoose.model("Item"));
Promise.promisifyAll(Item.prototype);
var connect = function () {
    var options = { server: { socketOptions: { keepAlive: 1 } } };
    var mongoUrl = "mongodb://" + config.mongo.host + ":" + config.mongo.port + "/" + config.mongo.db;
  mongoose.connect(mongoUrl, options);
}; 
connect();

Item.findAsync({item_id: "03010200400000a0bf00210"}).sort({ts:-1}).limit(1);
Possibly unhandled TypeError: Object [object Promise] has no method 'sort'
    at Object.module.exports.process (/Source/updater2/checkAndUpdate.js:88:75)
    at /Source/tellme/updater2/test1.js:25:20
    at tryCatch1 (/Source/updater2/node_modules/bluebird/js/main/util.js:43:21)
    at Promise$_callHandler [as _callHandler] (/Source/updater2/node_modules/bluebird/js/main/promise.js:627:13)
    at Promise$_settlePromiseFromHandler [as _settlePromiseFromHandler] (/Source/updater2/node_modules/bluebird/js/main/promise.js:641:18)
    at Promise$_settlePromiseAt [as _settlePromiseAt] (/Source/updater2/node_modules/bluebird/js/main/promise.js:804:14)
    at Promise$_settlePromises [as _settlePromises] (/Source/updater2/node_modules/bluebird/js/main/promise.js:938:14)
    at Async$_consumeFunctionBuffer [as _consumeFunctionBuffer] (/Source/updater2/node_modules/bluebird/js/main/async.js:75:12)
    at Async$consumeFunctionBuffer (/Source/updater2/node_modules/bluebird/js/main/async.js:38:14)
    at process._tickCallback (node.js:419:13)
Mongoose:item.find({ item_id: '03010200400000a0bf00210' }) { fields: undefined }  
4

3 回答 3

11

尝试这个

return Item.find({item_id: "03010200400000a0bf00210"}).sort({ts:-1}).limit(1).execAsync();
于 2014-07-17T09:10:31.867 回答
0
var options = {
        sort: { ts: -1 },
        limit: 1
    };    
var query = {item_id: "03010200400000a0bf00210"};
Item.findAsync(query,null,options).then(function(data){
     console.log(data);
    }).catch(function(err){
     console.log(err);
    });
于 2018-01-10T06:13:36.093 回答
-1

假设Item.findAsync返回的是一个承诺,而不是实际的结果,你需要等到结果返回后再对它们进行排序......

return Item.findAsync({item_id: "03010200400000a0bf00210"})
    then(function(items) {
        return items.sort({ts:-1}).limit(1);
    });
于 2014-07-16T13:06:01.897 回答