承诺没有方法'排序'

时间:2014-07-16 11:26:40

标签: node.js mongoose bluebird

我正在使用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 }  

3 个答案:

答案 0 :(得分:11)

试试这个

return Item.find({item_id: "03010200400000a0bf00210"}).sort({ts:-1}).limit(1).execAsync();

答案 1 :(得分: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);
    });

答案 2 :(得分:-1)

假设Item.findAsync正在返回一个承诺,并且不是实际结果,您需要等到结果返回后才排序......

return Item.findAsync({item_id: "03010200400000a0bf00210"})
    then(function(items) {
        return items.sort({ts:-1}).limit(1);
    });