我想对子对象的数据进行排序,注释:它们不是填充对象。
我的问题是如何使用字段中的 f_position 对 f_fields 对象进行排序?
model.js
var e_formSchema = new mongoose.Schema({
f_id: Number,
f_name: String,
f_fields: [{
f_f_id:Number,
f_position: Number,
f_obligatory :Boolean,
}]
}
, {collection: 'forms'});
数据示例
{
"f_id" : 3724,
"f_name" : "form 1",
"f_fields" : [
{
"f_f_id" : 64070,
"f_position" : 5,
"f_obligatory" : true,
},
{
"f_f_id" : 64071,
"f_position" : 6,
"f_obligatory" : true
},
{
"f_f_id" : 64204,
"f_position" : 1,
"f_obligatory" : true,
}
],
}
想要的结果
{
"f_id" : 3724,
"f_name" : "form 1",
"f_fields" : [
{
"f_f_id" : 64204,
"f_position" : 1,
"f_obligatory" : true,
}
{
"f_f_id" : 64070,
"f_position" : 5,
"f_obligatory" : true,
},
{
"f_f_id" : 64071,
"f_position" : 6,
"f_obligatory" : true
}
],
}
我想在同一个对象中对 f_fields 的子对象进行排序
我试过这段代码
getForm:function (id, callback){
var model = require("forms");
//model
model .find({f_id:3724}, function(err, forms) {
forms.sort({'f_fields.f_position':1})
.exec(function(err, doc){
if (err) {
callback(err) ;
} else {
callback(doc) ;
}
});
});
},
错误
has no method 'exec'
答案 0 :(得分:0)
你可以这样做:
db.forms.aggregate(
{ $match: {
f_id : 3724 }},
// Expand the array into a stream of documents
{ $unwind: '$f_fields' },
// Sort in descending order
{ $sort: {
'f_fields.f_position':-1
}}
)
输出:
{
"result" : [
{
"f_id" : 3724,
"f_name" : "form 1",
"f_fields" : {
"f_f_id" : 64204,
"f_position" : 1,
"f_obligatory" : true
}
},
{
"f_id" : 3724,
"f_name" : "form 1",
"f_fields" : {
"f_f_id" : 64070,
"f_position" : 5,
"f_obligatory" : true,
}
},
{
"f_id" : 3724,
"f_name" : "form 1",
"f_fields" : {
"f_f_id" : 64071,
"f_position" : 6,
"f_obligatory" : true,
}
}
],
"ok" : 1
}