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(17).lt(66)  // 17 < Person.age <66
      .where('likes').in(['vaporizing', 'talking'])//likes是vaporizing或者talking      .skip(10) //跳过前10条
      .limit(10)  //限制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);
        }
      })

你可能感兴趣的:(mongodb,mongoose,模糊查询,联表查询)