我只是想从 productSchema 中引用 accountSchema,但我收到了一个未定义的结果。我想我已经正确地引用了“帐户”,并且我正在正确地创建和保存产品。我的理解是 account 字段应该使用适当的 account objectId 填充自己,只是在模型中被引用。
//acount.model.js
const accountSchema = new Schema({
email: { type: String, unique: true, required: true },
passwordHash: { type: String, required: true },
title: { type: String, required: true },
firstName: { type: String, required: true },
lastName: { type: String, required: true },
acceptTerms: Boolean,
role: { type: String, required: true },
verificationToken: String,
verified: Date,
resetToken: {
token: String,
expires: Date
},
passwordReset: Date,
created: { type: Date, default: Date.now },
updated: Date
});
module.exports = mongoose.model('Account', accountSchema);
//product.model.js
const productSchema = new Schema({
title: { type: String, trim: true, required: true },
description: { type: String, trim: true, required: true },
category: { type: String, trim: true},
subCategory: { type: String, trim: true },
quantity: { type: Number, trim: true },
price: { type: Number, trim: true },
created: { type: Date, default: Date.now },
updated: Date,
account: { type: Schema.Types.ObjectId, ref: 'Account' }
});
module.exports = mongoose.model('Product', productSchema);
//products.controller.js
//routes
router.post('/', authorize([Role.Admin, Role.Vendor]), createSchema, create);
function createSchema(req, res, next) {
const schema = Joi.object({
title: Joi.string().required(),
description: Joi.string().required(),
category: Joi.string(),
subCategory: Joi.string(),
quantity: Joi.number(),
price: Joi.number()
});
validateRequest(req, next, schema);
}
function create(req, res, next) {
productService.create(req.body)
.then(product => res.json(product))
.catch(next);
}
//product.service.js
async function create(params) {
const product = new db.Product(params);
// save account
await product.save();
// res.json(product);
console.log(basicDetails(product));
return basicDetails(product);
}
function basicDetails(product) {
const { id, title, description, category, subCategory, quantity, price, account } = product;
return { id, title, description, category, subCategory, quantity, price, account };
}
//console.log output of basicDetails(product)
{
id: '600614014d927f29a0fbb162',
title: 'delete from mcjaggerrrrrrrr6789',
description: 'testing delete from role.vendor mcjaggerrrrrrrrrr',
category: undefined,
subCategory: undefined,
quantity: undefined,
price: undefined,
account: undefined
}
category、subCat、quant 和 price 都未定义,因为我没有为它们输入值,但 account 未定义,我不知道为什么。任何帮助表示赞赏!