国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > JS > 正文

nodejs+mongodb aggregate級聯查詢操作示例

2024-05-06 16:43:10
字體:
來源:轉載
供稿:網友

本文實例講述了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程序設計有所幫助。


注:相關教程知識閱讀請移步到JavaScript/Ajax教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 普洱| 利川市| 丽江市| 会同县| 蕲春县| 浮山县| 延津县| 两当县| 常德市| 沁水县| 中方县| 台安县| 赤峰市| 二连浩特市| 盘锦市| 莲花县| 浮梁县| 金乡县| 新蔡县| 平远县| 平邑县| 鄄城县| 鹤庆县| 井陉县| 北辰区| 客服| 金溪县| 耒阳市| 正宁县| 五大连池市| 万年县| 江油市| 方城县| 长沙县| 偏关县| 伊宁市| 宜州市| 六安市| 当涂县| 灯塔市| 英山县|