天天看點

mongoose模糊查詢及聯表查詢等

原文位址:https://segmentfault.com/a/1190000006126679

mongoose的一些進階用法:

1 populate聯表查詢

首先,我們定義三個Schema

drawApply = new Schema({
    salesId: { type: Schema.ObjectId, ref: 'sales' },
    money: Number,
    status: { type: Number, default: 0 },
    createTime: { type: Date, default: Date.now }
});

sales = new Schema({
    name: { type: String, required: true, unique: true },
    pwd: String,
    phone: String,
    merchant: { type: Schema.ObjectId, ref: 'merchant' },
    status: { type: Number, default: 0 }
});

merchant = new Schema({
    name: String,
    sname: String,
    type: String
});      

  傳回的結果中除了drawApply表的資料外,還會包含salesId中_id,name,phone,merchant四個屬性的值(注:需要檢視什麼屬性就在第二個參數中明示,若populate方法中隻有salesId參數,則會将sales表中所有屬性傳回)。但是merchant屬性的值是以ObjectId的形式顯示的,如果想知道對應的merchant其它屬性的值,則需要再次使用到嵌套的populate。代碼如下:

drawApply.find().populate({
    path: 'salesId',
    select: '_id name phone merchant',
    model: 'sales',
    populate: {
        path: 'merchant',
        select: '_id sname',
        model: 'merchant'
    }).sort({createTime: -1}).exec(function(err, list) {
  // list of drawApplies with salesIds populated and merchant populated
});      

  如果drawApply表中還存在其它ObjectId類型的字段,則可以在populate方法後面繼續跟其它的populate,使用方法相同,如:

drawApply.find().populate({
    path: 'salesId',
    select: '_id name phone merchant',
    model: 'sales',
    populate: {
        path: 'merchant',
        select: '_id sname',
        model: 'merchant'
    })
    .populate('approver', 'name')//這裡是簡寫方式, {path:'approver',select:'name'}
    .populate('operator', 'name')
    .sort({createTime: -1}).exec(function(err, list) {
  // list of drawApplies with salesIds populated and merchant populated
});      

2 複雜查詢

以下是一個複雜查詢,基本包括了所有的查詢用法

Person
      .find({ occupation: /host/ }) 
      .where('name.last').equals('Ghost')   // Person.name.last是Ghost
      .where('age').gt().lt()  // 17 < Person.age <66
      .where('likes').in(['vaporizing', 'talking'])//likes是vaporizing或者talking                    .skip(10) //跳過前10條
      .limit()  //限制10條記錄              .sort({time:-1})  //根據time的倒序排
      .select('name occupation') //選擇name和occupation字段
      .exec(callback);
           

3 模糊比對

有時候在項目中需要搜尋功能,而搜尋功能的實作必須用模糊比對,這個時候可以使用or進行多字段比對,但速度比較慢,大系統最好使用專業的搜尋方法

or表示在數組裡的條件滿足一個即可,$regex表示一個正規表達式,比對了key,同時,加入了$option的$i表示忽略大小寫

Job.find({
        $or: [
          {'description': {'$regex': key, $options: '$i'}},
          {'city': {'$regex': key, $options: '$i'}},
          {'name': {'$regex': key, $options: '$i'}}]
      })
      .populate('JobType', 'name')
      .exec(function (err, jobs) {
        if (err) {
          callback(err);
        } else {
          callback(null, jobs);
        }
      })