我有三种不同的模型:产品,商店和用户 我要完成的工作是用Shop和User填充getProduct路由。
router.route('/:productId').get(productController.getProduct);
产品型号
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const productSchema = new Schema({
name: {
type: String,
trim: true,
required: [true, 'Name is required']
},
image: {
data: Buffer,
contentType: String
},
description: {
type: String,
trim: true
},
category: {
type: String
},
quantity: {
type: Number,
default: 0,
required: [true, 'Quantity is required']
},
price: {
type: Number,
required: [true, 'Price is required']
},
updated: Date,
created: {
type: Date,
default: Date.now
},
shop: { type: mongoose.Schema.ObjectId, ref: 'Shop' },
owner: [{ type: mongoose.Schema.ObjectId, ref: 'User', required: true }]
});
const Product = mongoose.model('Product', productSchema);
module.exports = Product;
用户模型
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const validator = require('validator');
const bcrypt = require('bcryptjs');
const userSchema = new Schema({
name: {
type: String,
trim: true,
required: [true, 'Name is required']
},
email: {
type: String,
required: [true, 'Please enter a valid email'],
unique: true,
lowercase: true,
validate: [validator.isEmail, 'Please enter a valid email']
},
role: {
type: String,
default: 'user',
enum: ['owner', 'seller', 'user', 'admin']
},
password: {
type: String,
required: [true, 'Please enter a password'],
minlength: 8,
select: false
},
seller: {
type: Boolean,
default: false
},
updated: Date,
active: {
type: Boolean,
default: true,
select: false
},
created: {
type: Date,
default: Date.now
}
});
产品负责人
exports.getProduct = (req, res, next) => {
Product.findById(req.params.productId)
.populate('shop', 'name _id')
.populate('owner', 'name _id')
.exec((err, product) => {
if (err || !product)
return res.status('400').json({
error: 'Product not found'
});
res.status(200).json(product);
});
};
用户控制器
exports.getUser = asyncMiddleware(async (req, res, next) => {
const user = await User.findById(req.params.userId);
if (!user) {
return next(new ErrorResponse('No user found!', 404));
}
res.status(200).json({ user });
});
但是,商店填充正常,我无法弄清楚为什么老板不填充。
这是邮递员中的 getProduct 路线
{
"image": {...
},
"quantity": 6,
"owner": [],
"_id": "5e67a428f7927504e87d30de",
"name": "calculator",
"description": "a calculator for senior students",
"category": "school",
"price": 150,
"created": "2020-03-10T14:28:56.214Z",
"shop": {
"_id": "5e5e0eb64a6a2d0766eda2cb",
"name": "a basket"
},
"__v": 0
}