1. 程式人生 > >nodejs+mongoose()連表查詢

nodejs+mongoose()連表查詢

首先,我們定義三個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')
    .populate('operator', 'name')
    .sort({createTime: -1}).exec(function(err, list) {
  // list of drawApplies with salesIds populated and merchant populated
});