bp123
bp123

Reputation: 3427

findOneAndUpdate document with array

Two questions here.

  1. What is the correct way to findOneAndUpdate when there is an array? The example below errors with err MongooseError [CastError]: Cast to embedded failed for value.
  2. Should you arrays of objects become separate collections?

* Example *

var ProductSchema = new Schema({
  _id: Schema.Types.ObjectId,
  product_name: String
});

var purchaseOrderSchema = new Schema(
  {
    purchaseOrderNo: Number,
    products: [ProductSchema]
  }
);

const purchaseOrder = new PurchaseOrder(req.body);

PurchaseOrder.findOneAndUpdate(
  { _id: req.body._id },
  {
    $set: req.body,
    $push: req.body.products
  },
  { upsert: true, new: true }
)
.then((result) => {
  console.log('result', result);
  res.status(200).json(result);
})
.catch((err) => {
  console.log('err', err);
  res.status(500).json({ error: err });
});


const body = {
  _id: 'skjdhflksjdf',
  purchaseOrderNo: 1,
  products: [
    {
      _id: '111',
      product_name: 'Cup'
    },
    {
      _id: '222',
      product_name: 'Spoon'
    }
  ]
}

Upvotes: 0

Views: 143

Answers (1)

vishnu
vishnu

Reputation: 2011

In the ProductSchema the type of _id field to set to ObjectId. The product id 111 and 222 are not a valid ObjectId and it fails to cast it. You can update the type of _id in ProductSchema to Number for this to work

var ProductSchema = new Schema({
  _id: Number,
  product_name: String
});

Upvotes: 1

Related Questions