我将Node and Express与Mongoose结合使用,并且试图在其中填充'product'属性
const item = new CartItem({ _pId: id, product: id });
所以我想做的基本上是这样,但它不起作用
const item = new CartItem({ _pId: id, product: id });
item.populate({
path: 'cart.products.product',
model: 'Product',
select: '-inStock -_userId -__v',
});
this.markModified('cart.products');
this.cart.products.push(item);
return this.save();
我也不确定这部分是否是“ this.markModified('cart.products');”是必需的。
这是整个方法
schema.methods.addUpdateRemoveCartItem = function (id, newQuantity) {
let productsIndex;
const productIsInCart = this.cart.products.some((el) => {
productsIndex = this.cart.products.indexOf(el);
return el._pId._id.equals(id);
});
if (productIsInCart) {
if (newQuantity > 0) {
this.cart.products[productsIndex].qty = +newQuantity;
} else if (newQuantity == 0) {
this.cart.products.splice(productsIndex, 1);
} else {
this.cart.products[productsIndex].qty += 1;
}
this.markModified('cart.products');
} else {
/* doesnt populate */
const item = new CartItem({ _pId: id, product: id });
item.populate({
path: 'cart.products.product',
model: 'Product',
select: '-inStock -_userId -__v',
});
this.markModified('cart.products');
this.cart.products.push(item);
return this.save();
}
这是模型
const mongoose = require('mongoose');
const CartItem = require('../models/cart.model');
const Product = require('../models/product.model');
const schema = new mongoose.Schema(
{
name: {
type: String,
trim: true,
required: true,
maxLength: 30,
minlength: 2,
},
email: {
type: String,
trim: true,
required: true,
},
cart: {
products: { type: Array, of: CartItem },
totalQuantity: { type: Number, min: 0, default: 0 },
totalPrice: { type: Number, min: 0, default: 0 },
},
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true },
}
);
schema.methods.addUpdateRemoveCartItem = function (id, newQuantity) {// specified above}
const User = mongoose.model('User', schema);
module.exports = User;
const mongoose = require('mongoose');
const schema = new mongoose.Schema({
_id: false,
_pId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Product',
trim: true,
required: true,
},
product: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Product',
trim: true,
required: true,
},
qty: {
type: Number,
trim: true,
required: true,
max: 10000,
min: 0,
default: 1,
},
});
const Cart = mongoose.model('Cart', schema);
module.exports = Cart;