1、mongoose中一个数据模型Product
(商品)关联另外一个数据模型Brand
(品牌)需要使用ref
,关联查询使用populate
Product模型
new mongoose.Schema({// 商品名称name: { type: String, required: true, validate: /\S+/ },// 商品内容content: { type: String, required: true, validate: /\S+/ },// 关联的品牌brand: { type: mongoose.Schema.Types.ObjectId, ref: 'Brand' }...
Brand模型
new mongoose.Schema({// 品牌name: { type: String, required: true, validate: /\S+/ },// 品牌图片img: { type: String, required: true, validate: /\S+/ }...
2、查询使用populate
// 过滤条件
const options = {sort: { _id: -1 },page: Number(page),limit: Number(size),// populate: ['brand', 'tag'],populate: [{ path: 'brand', select: 'name' }, 'tag'],select: '-password -content'
};// 查询参数const keywordReg = new RegExp(keyword)const query = {"$or": [{ 'name': keywordReg },{ 'slug': keywordReg },{ 'description': keywordReg }]}const ones = await Product.paginate(query, options)
3、注意上段代码中
populate: ['brand', 'tag'],
brand
所有字段都返回
populate: [{ path: 'brand', select: 'name' }, 'tag'],
brand
返回name字段