当前位置: 移动技术网 > IT编程>开发语言>JavaScript > nodejs+mongodb aggregate级联查询操作示例

nodejs+mongodb aggregate级联查询操作示例

2018年03月30日  | 移动技术网IT编程  | 我要评论

本文实例讲述了nodejs+mongodb 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 } ]

希望本文所述对大家nodejs程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网