1

I am trying to store in an array of ID's the new information from req.body but I am only able to update the new info. I think I need to use the rest operator but not exactly sure where. Any hints?

What I am looking to get

pets: [allpreviousObjectID, newObjectID]

but at this moment only getting:

pets: [newObjectId]

this is the part of the Model Schema that I created for this field:

pets: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Pets' }]

this is the function I am using

router.post('/register', [isAuthenticated], async (req, res, next) => {
  try {
    const newPet = new PetsModel({
      name: req.body.name,
      age: req.body.age,
      weight: Number(req.body.weight),
      img: req.body.img,
      breed: req.body.breed,
      dateArrivalInShelter: req.body.dateArrivalInShelter,
      about: req.body.about,
      status: req.body.status,
      shelterId: req.user
    });

    await newPet.save();

    await ShelterModel.findByIdAndUpdate(req.user, {
      pets: newPet
    });

    res.status(201).json({
      success: true,
      data: 'Pet Created'
    });
  } catch (error) {
    next(error);
  }
});
elisa
  • 229
  • 1
  • 2
  • 8
  • 1
    Does this answer your question? [Push items into mongo array via mongoose](https://stackoverflow.com/questions/33049707/push-items-into-mongo-array-via-mongoose) – MatsLindh May 07 '21 at 18:07
  • It perfectly does! thank you! @MatsLindh – elisa May 07 '21 at 18:11

0 Answers0