问题描述
我将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,});
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,cart: {
products: { type: Array,of: CartItem },totalQuantity: { type: Number,min: 0,default: 0 },totalPrice: { type: Number,{
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',product: {
type: mongoose.Schema.Types.ObjectId,qty: {
type: Number,max: 10000,default: 1,});
const Cart = mongoose.model('Cart',schema);
module.exports = Cart;
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)