好吧,我有以下几个Shemas:
var BrandSchema = new Schema({ name: { type: String, required: true, index: { unique: true }, lowercase: true }, logo: { type: ObjectId, ref: 'Image' } }); var FollowActionSchema = new Schema({ 'actionDate': { type: Date, 'default': Date.now }, 'brand': { type: ObjectId, ref: 'Brand' }, 'performer': { type: ObjectId, ref: 'User' }, 'type': String // followUser, folloBrand, followMerchant });
我想要的是让用户跟踪品牌,按品牌名排序,所以对于这样做,我对FollowAction进行查询,找到用户所做的所有FollowAction,然后填充brand字段。
所以问题是我不能为品牌名的查询排序,我知道的唯一方法是返回所有文档并从nodejs应用程序中对它们进行排序。有人知道我怎么能那样做吗??或者我是否应该改变shema结构??
我所做的查询是:
async.waterfall([ function findActions(next) { var options = { query: { performer: userId, $or: [{ type: 'followBrand' }, { type: 'followMerchant' }] }, projection: { actionDate: 1, brand: 1, merchant: 1, type: 1 }, sort: '-actionDate', pagination: pagination }; utils.limitQuery('FollowAction', options, next); }, function inflate(actions, next) { total = actions.count; var options = { projection: { name: 1, _id: 1, username: 1 } }; async.eachSeries(actions.result, function(action, done) { async.waterfall([ function inflateAction(done) { action.inflate(options, done); }, function addToArray(item, done) { trusted.push({ _id: item._id, name: utils.capitalize(item.name || item.username), type: item.name ? 'brand' : 'merchant' }); return done(null, item); } ], done); }, next); } ], function(err) { callback(err, trusted, total); });
Mongoose API似乎确实支持对填充字段进行排序,但有一个bug完全破坏了它:https://github.com/automattic/Mongoose/issues/2202。你得到了一个结果,但它是完全错误的。
对于少量数据,可以使用Javascript array.prototype.sort()对结果数组进行排序。但请记住,这将直接修改排序数组。
在本例中,我所做的是为要排序的模型的模式添加一个排序键属性。对于您的示例,可以执行以下操作:
var FollowActionSchema = new Schema({
// ...
'brandSortKey': { type: String },
'brand': {
type: ObjectId,
ref: 'Brand'
},
// ...
});
这并不完美,因为您必须自己使用正确的键显式设置此属性:
var FollowAction = Model('FollowAction', FollowActionSchema);
var aBrand = // some brand object
var f = new FollowAction({
brand: aBrand._id,
brandSortKey: aBrand.name
// other properties
});
但是,您可以直接通过Mongoose API(或MongoDB)进行排序:
FollowAction.find({})
.sort({ brandSortKey:1 })
.exec(function (err, sortedResults) {
// do something with sorted results.
});
从这个简单的例子中得到这个想法
Post.find({'_id': userId})
.limit(10)
.skip(0)
.sort({'created_at':-1}) // this is used to sort
.exec(function(error, result){
if(!error){
// console.log(result);
res.send({data:result});
} else{
console.log(error);
}
});