0

I have Category mongoose document and I want to update his products.Every time on update products just rewrite them and I have only the last put record.How can I populate products?

const category = new mongoose.Schema({
  
  products: [{ type: mongoose.Schema.Types.ObjectId, ref: "Product" }],
  
});

    module.exports = mongoose.model("Category", category);

    exports.updateCategory = catchAsyncErrors(async (req, res, next) => {
  let category = await Category.findById(req.params.id);


  category = await Category.findByIdAndUpdate(req.params.id, req.body, {
    new: true,
    runValidators: true,
    useFindAndModify: false,
  })

  res.send(200).json({
    success: true,
    category
  });
});
  • Does this answer your question? [Push items into mongo array via mongoose](https://stackoverflow.com/questions/33049707/push-items-into-mongo-array-via-mongoose) – Mohamed Oraby May 01 '21 at 14:52
  • "Cast to [ObjectId] failed for value \"[{\"products\":\"608d588fbf0d1b761cf567cf\"}]\" at path \"products.0\"", –  May 01 '21 at 15:04

1 Answers1

0

Assuming your products are called products in body:

category = await Category.findByIdAndUpdate(req.params.id, { $push: { products: req.body.products } }, {
  new: true,
  runValidators: true,
  useFindAndModify: false,
})
Mohamed Oraby
  • 916
  • 3
  • 8
  • 14
  • Ok with postman I sending this { "products":["kmnkjnjjhu"]} but gives error again.Server started on port 4000 in DEVELOPMENT Mongo db connected with host: localhost ---------------------------------------- { products: [ '608d588fbf0d1b761cf567cf' ] } Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client –  May 01 '21 at 15:27
  • can you update your code in the question? – Mohamed Oraby May 01 '21 at 15:29
  • I use same code with your example.The products are updated corectly but now throws this (node:3864) DeprecationWarning: Mongoose: `findOneAndUpdate()` and `findOneAndDelete()` without the `useFindAndModify` option set to false are deprecated. See: https://mongoosejs.com/docs/deprecations.html#findandmodify (Use `node --trace-deprecation ...` to show where the warning was created) express deprecated res.send(status): Use res.sendStatus(status) –  May 01 '21 at 16:02
  • 1
    set useFindAndModify to false in your mongoose.connect `mongoose.connect('mongodb://localhost:27017/exampleDB', {useFindAndModify: false});` – Mohamed Oraby May 01 '21 at 16:05
  • Thanks. Also I rewrite res.send with res.satus –  May 01 '21 at 16:12
  • I didn't notice that it was res.send(200) not res.status(200), sorry – Mohamed Oraby May 01 '21 at 16:14