现在我在一个商店项目中工作,我有一个关于猫鼬js中的模型和模式以及如何在我们的项目中使用它们的问题。
订单模型
在CartItemSchema中,我还引用产品和商店
在OrderSchema中,我引用的是CartItemSchema
const mongoose = require('mongoose');
const CartItemSchema = new mongoose.Schema({
product: [{ type: mongoose.Schema.ObjectId, ref: 'Product' }], <-- Product Schema
quantity: Number,
shop: [{ type: mongoose.Schema.ObjectId, ref: 'Shop' }], <-- Shop Schema
status: {
type: String,
default: 'Not processed',
enum: ['Not processed', 'Processing', 'Shipped', 'Delivered', 'Cancelled']
}
});
const OrderSchema = new mongoose.Schema({
products: [CartItemSchema], <-- CartItemSchema Schema
customer_name: {
type: String,
trim: true
},
customer_email: {
type: String,
trim: true,
match: [/.+.+\..+/, 'Please fill a valid email address']
},
deliveryAddress: {
street: { type: String, required: 'Street is required' },
city: { type: String, required: 'City is required' },
state: { type: String, required: 'State is required' },
zipcode: { type: String, required: 'Zip Code is required' },
country: { type: String, required: 'Country is required' }
},
payment_id: {},
updated: Date,
created: {
type: Date,
default: Date.now
},
user: { type: mongoose.Schema.ObjectId, ref: 'User' }
});
const Order = mongoose.model('Order', OrderSchema);
module.exports = Order;
创建订单控制器
exports.createOrder = asyncMiddleware(async (req, res, next) => {
const order = new Order({
user: req.user,
deliveryAddress: req.body.deliveryAddress,
products: req.body.products, <-- referencing the products in OrderSchema
customer_name: req.body.customer_name,
customer_email: req.body.customer_email
});
order.save((err, result) => {
if (err) {
return next(new ErrorResponse(err, 400));
}
res.status(200).json(result);
});
});
但是,我的问题是,当我根据在订单模型中指定的字段创建新的订单时,如何引用产品字段,到目前为止,我已经做了类似的事情。 ..
products: req.body.products,
但是,这不能按预期方式工作,我只能获取产品的ObjectId,而shop的ObjectId是一个空数组。