好吧,我有以下 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,然后填充品牌字段。
所以问题是我无法对品牌名称的查询进行排序,我知道的唯一方法是返回所有文档并从 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 似乎确实支持对填充字段进行排序,但有一个错误完全破坏了它:https://github.com/Automattic/mongoose/issues/2202 .您得到了一个结果,但它显然是错误的。
对于少量数据,可以使用 Javascript 对结果数组进行排序 Array.prototype.sort() .请记住,这会直接修改已排序的数组。
在这种情况下,我所做的是将排序键属性添加到您要排序的模型的架构中。对于您的示例,您可以这样做:
var FollowActionSchema = new Schema({
// ...
'brandSortKey': { type: String },
'brand': {
type: ObjectId,
ref: 'Brand'
},
// ...
});
这并不完美,因为您必须自己使用正确的 key 显式设置此属性:
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.
});
关于node.js - Mongoose 按填充字段排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31180455/
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢
我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr
我有一个驼峰式字符串,例如:JustAString。我想按照以下规则形成长度为4的字符串:抓取所有大写字母;如果超过4个大写字母,只保留前4个;如果少于4个大写字母,则将最后大写字母后的字母大写并添加字母,直到长度变为4。以下是可能发生的3种情况:ThisIsMyString将产生TIMS(大写字母);ThisIsOneVeryLongString将产生TIOV(前4个大写字母);MyString将生成MSTR(大写字母+tr大写)。我设法用这个片段解决了前两种情况:str.scan(/[A-Z]/).first(4).join但是,我不太确定如何最好地修改上面的代码片段以处理最后一种
我几天前在我的rubyonrails2.3.2上安装了Sphinx和Thinking-Sphinx,基本搜索效果很好。这意味着,没有任何条件。现在,我想用一些条件过滤搜索。我有公告模型,索引如下所示:define_indexdoindexestitle,:as=>:title,:sortable=>trueindexesdescription,:as=>:description,:sortable=>trueend也许我错了,但我注意到只有当我将:sortable=>true语法添加到这些属性时,我才能将它们用作搜索条件。否则它找不到任何东西。现在,我还在使用acts_as_tag
假设您编写了一个类Sup,我决定将其扩展为SubSup。我不仅需要了解你发布的接口(interface),还需要了解你的私有(private)字段。见证这次失败:classSupdefinitialize@privateField="fromsup"enddefgetXreturn@privateFieldendendclassSub问题是,解决这个问题的正确方法是什么?看起来子类应该能够使用它想要的任何字段而不会弄乱父类(superclass)。编辑:equivalentexampleinJava返回"fromSup",这也是它应该产生的答案。 最佳答案
我使用rails3.1+rspec和factorygirl。我对必填字段(validates_presence_of)的验证工作正常。我如何让测试将该事实用作“成功”而不是“失败”规范是:describe"Addanindustrywithnoname"docontext"Unabletocreatearecordwhenthenameisblank"dosubjectdoind=Factory.create(:industry_name_blank)endit{shouldbe_invalid}endend但是我失败了:Failures:1)Addanindustrywithnona
我需要用任何语言编写一个算法,根据3个因素对数组进行排序。我以度假村为例(如Hipmunk)。假设我想去度假。我想要最便宜的地方、最好的评论和最多的景点。但是,显然我找不到在所有3个中都排名第一的方法。Example(assumingthereare20importantattractions):ResortA:$150/night...98/100infavorablereviews...18of20attractionsResortB:$99/night...85/100infavorablereviews...12of20attractionsResortC:$120/night
我正在尝试按Rails相关模型中的字段进行排序。我研究的所有解决方案都没有解决如果相关模型被另一个参数过滤?元素模型classItem相关模型:classPriority我正在使用where子句检索项目:@items=Item.where('company_id=?andapproved=?',@company.id,true).all我需要按相关表格中的“位置”列进行排序。问题在于,在优先级模型中,一个项目可能会被多家公司列出。因此,这些职位取决于他们拥有的company_id。当我显示项目时,它是针对一个公司的,按公司内的职位排序。完成此任务的正确方法是什么?感谢您的帮助。PS-我