问题
I am using Mongoose with Bluebird and am hitting an Error when using a query that includes a sort on a time stamp. I am trying to retrieve only the most recent entry. The query works when using the built in Promises.
Any ideas? Thanks!
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 }
回答1:
Try this
return Item.find({item_id: "03010200400000a0bf00210"}).sort({ts:-1}).limit(1).execAsync();
回答2:
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);
});
回答3:
Assuming Item.findAsync
is returning a promise, and not the actual results, you need to wait until the results are returned before you sort them...
return Item.findAsync({item_id: "03010200400000a0bf00210"})
then(function(items) {
return items.sort({ts:-1}).limit(1);
});
来源:https://stackoverflow.com/questions/24779597/promise-has-no-method-sort