这次给大家带来aggregate级联查询实现步骤,aggregate级联查询实现的注意事项有哪些,下面就是实战案例,一起来看一下。
最近完成了一个nodejs+mongoose的项目,碰到了mongodb的级联查询操作。情形是实现一个排行榜,查看某个公司(organization)下属客户中发表有效文ruan章wen最多的前十人。
account表:公司的信息单独存在一个account表里。
var accountschema = new schema({
loginname: {type: string},
password: {type: string},
/**
* 联系方式
*/
//账户公司名
comname: {type: string},
//地址
address: {type: string},
//公司介绍
intro: {type: string}
});
mongoose.model('account', accountschema);
cusomer表:公司的客户群。
var customerschema = new schema({
/**
* 基本信息
*/
//密码
password: {type: string},
//归属于哪个account
belongtoaccount: {type: objectid, ref: 'account'},
//手机号,登录用
mobile: {type: string},
//真实姓名
realname: {type: string}
});
customerschema.index({belongtoaccount: 1, mobile: 1}, {unique: true});
mongoose.model('customer', customerschema);
article表
var articleschema= new schema({
belongtoaccount: {type: objectid, ref: 'account'},
title: {type: string},
text: {type: string},
createtime: {type: date, default: date.now},
author: {type: objectid, ref: 'customer'},
//0,待确认,1 有效 ,-1 无效
status: {type: number, default: 0}
});
articleschema.index({belongtoaccount: 1, createtime:-1,author: 1}, {unique: false});
mongoose.model('article', articleschema);
这里要做的就是,由accountid→aggregate整理软文并排序→级联author找到作者的姓名及其他信息。
代码如下:
exports.getranklist = function (accountid, callback) {
aticlemodel.aggregate(
{$match: {belongtoaccount: mongoose.types.objectid(accountid), status: 1}},
{$group: {_id: {customerid: $author}, number: {$sum: 1}}},
{$sort: {number: -1}}).limit(10).exec(function (err, aggregateresult) {
if(err){
callback(err);
return;
}
var ep = new eventproxy();
ep.after('got_customer', aggregateresult.length, function (customerlist) {
callback(null, customerlist);
});
aggregateresult.foreach(function (item) {
customer.findone({_id: item._id.customerid}, ep.done(function (customer) {
item.customername = customer.realname;
item.customermobile=cusomer.mobile;
// do someting
ep.emit('got_customer', item);
}));
})
});
};
返回的结果格式(这里仅有两条记录,实际为前十):
[ { _id: { customerid: 559a5b6f51a446602032fs21 }, number: 5,
customername: 'test2',
mobile:22 } ,
{ _id: { customerid: 559a5b6f51a446602041ee6f }, number: 1,
customername: 'test1',
mobile: 11 } ]
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
js给动态创建元素添加事件步骤详解
vue上传图片到数据库在前端页面展示
以上就是aggregate级联查询实现步骤的详细内容。