заполнить вложенный массив объектов мангуст

Я пытался заполнить продукты в моей корзине. Моя модель корзины -

const ProductSchema = new mongoose.Schema({
  product: { type: mongoose.Schema.Types.ObjectId, ref: 'Product'},
  quantity: Number
});
const CartSchema = new mongoose.Schema({
  userId: mongoose.Schema.Types.ObjectId,
  products: [ProductSchema]
});

Я пытаюсь получить значение корзины следующим образом:

let getCart = async (userId) => {
  let res = await Cart.find({ userId: userId }).populate('products.product')
  return res;
};

Выход -

{
  userId: xyz,
  products:[
    product: null,
    quantity:1
  ]
}

Ожидаемый результат -

{ 
  userId: xyz,
  products:[
    product: {
      name: 'product name', 
      description:'',
      ...
    },
    quantity:1
  ]
}

person Komal Bansal    schedule 06.05.2019    source источник
comment
Возможный дубликат Mongoose, заполняющий массив вложенных документов   -  person Vikash Singh    schedule 16.05.2019


Ответы (2)


Вам нужно заполнить только products и выбрать product для отображения из заполненного массива.

person Shivam Pandey    schedule 06.05.2019

Я думаю, достаточно просто заполнить продукт.

let getCart = async (userId) => {
  let res = await Cart.find({ userId: userId }).populate('products')
  return res;
};
person Shivani Tyagi    schedule 06.05.2019