mongoosesorting填充字段
以及我有以下shemas:
var BrandSchema = new Schema({ 名称: { 键入:String, 要求:真, 索引:{ 独特:真实 }, 小写:真 }, 商标: { 键入:ObjectId, ref:'Image' } }); var FollowActionSchema = new Schema({ 'actionDate':{ 键入:date, 'default':Date.now }, '牌': { 键入:ObjectId, ref:'品牌' }, “表演者”:{ 键入:ObjectId, ref:'User' }, 'type':string//跟随用户,跟随品牌,跟随买家 });
我想要的是让用户跟随品牌,按品牌名称sorting,所以为了做到这一点,我做了FollowAction的查询,并find用户所做的所有FollowActions,然后填充品牌字段。
所以问题是我不能sorting查询的品牌名称,唯一的方法,我知道这样做是通过返回所有文件,并从nodejs应用程序sorting。 任何人都知道我该怎么做? 或者如果我应该改变shema结构?
我做的查询是:
async.waterfall([ 函数findActions(next){ var options = { 查询:{ 执行者:userId, $或:[{ 键入:'followBrand' },{ 键入:“followMerchant” }] }, 投影:{ actionDate:1, 品牌:1, 商家:1, 键入:1 }, sorting:'-actionDate', 分页:分页 }; utils.limitQuery('FollowAction',options,next); }, 函数膨胀(actions,next){ total = actions.count; var options = { 投影:{ 名称:1, _id:1, 用户名:1 } }; async.eachSeries(actions.result,function(action,done){ async.waterfall([ 函数inflateAction(done){ action.inflate(options,done); }, function addToArray(item,done){ trusted.push({ _id:item._id, 名称:utils.capitalize(item.name || item.username), 键入:item.name? '品牌':'商人' }); 返回完成(null,item); } 完成); }, 下一个); } ],函数(err){ callback(err,trusted,total); });
Mongoose API似乎支持对填充字段进行sorting,但有一个错误完全打破: https : //github.com/Automattic/mongoose/issues/2202 。 你会得到一个结果,但这只是错误的。
对于less量数据,可以使用Javascript Array.prototype.sort()对结果数组进行sorting。 请记住,这直接修改sorting的数组。
在这种情况下,我所做的是为要sorting的模型添加sorting关键字属性。 举个例子,你可以这样做:
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)进行sorting:
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); } });