以下从建表到查询:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const ObjectId = Schema.Types.ObjectId
const ProductSchema = new mongoose.Schema({
productName:String,
productCatalog: {
type: ObjectId,
ref: 'ProductCatalog' //类目
},
productMainPicture:String,
productPrice:Number,
productTotal:Number,
productSalesTotal:Number,
productStatus:Boolean,
productOrigin:String, //产地
brandName:{
type: ObjectId,
ref: 'Brand' //品牌
},
createdAt: {
type: Date,
default: Date.now
},
updatedAt: {
type: Date,
defalut: Date.now
}
});
module.exports = ProductSchema
Model
var mongoose = require('mongoose')
var ProductSchema = require('./../schemas/product')
var Product = mongoose.model('Product', ProductSchema)
module.exports = Product
查询
var express = require('express')
var productRouter = express.Router()
var Product = require('./../app/models/product')
productRouter.route(`/`)
.get((req,res) => {
Product.find({})
.sort({'_id':-1})
.limit(10)
.populate('ProductCatalog catalogName')
.populate('Brand','brandName brandDescription')
.then((data) => {
if (data) {
res.json({
status: '200',
msg: '',
result: data
})
} else {
res.json({
status: '0',
msg: '没有product',
result: ''
})
}
})
})
module.exports = productRouter
问题描述:
product 表关联查询 ProductCatalog Brand 两张表,两张表中只查询显示 catalogName brandName,但实际情况是查询并显示关联两张表的 id ,需要的字段内容没有显示出来。
{
"status": "200",
"msg": "",
"result": [
{
"_id": "60e134503b6ff901bc7c4114",
"productName": "水杯",
"productCatalog": "60d0aa16183981825073b21e",
"productMainPicture": "",
"productTotal": 88,
"productPrice": 77,
"productSalesTotal": 99,
"productStatus": false,
"productOrigin": "上海",
"brandName": "60e123a2b13e944620a9e2b4",
"createdAt": "2021-07-04T04:08:48.359Z",
"__v": 0
},
{
"_id": "60e1306d8c70524a88fd469f",
"productName": "萝卜干",
"productCatalog": "60d0a7fc3c322069dcfd007d",
"productMainPicture": "",
"productTotal": 55,
"productPrice": 44,
"productSalesTotal": 66,
"productStatus": true,
"productOrigin": "安徽",
"brandName": "60e1242cb13e944620a9e2b5",
"createdAt": "2021-07-04T03:52:13.223Z",
"__v": 0
},
]
}
我记得之前可以用 .populate('Model 查询字段') 这种方法查询的,但是不知道为什么现在不可以了,求指点,非常感谢!