How to keep Mongoose document position when editing subdocument

#1

I want to edit a subdocument while keeping the document position in the collection.

I use findOne to retrieve the document then Object.assign to edit the document subdocument. Then, I save the document.

I’ve read here things about position but don’t find how to apply to my case Mongoose find/update subdocument

async editSecondLevel (req, res, next) {
    var body = _.pick(req.body, ['_id', 'name', 'icon', 'category'])

    FirstLevel.findOne({ 'secondLevels._id': body._id }, function (err, firstLevel) {
      if (err) return next(err);
      Object.assign(firstLevel.secondLevels.id(body._id), body)
      firstLevel.save().then(() => {
        return res.send(firstLevel)
      }).catch((e) => {
        res.status(400).send(e)
      })
    }).catch((e) => {
      res.status(400).send(e)
    })
  }

Sometimes, it keep the document (firstLevel) position. Sometimes, it doesn’t.

I’ve read here MongoDB field order and document position change after update that “if your update increases the size of the document beyond the size originally allocated the document will be moved to the end of the collection”

Is it possible to keep the position anyway ?

Thanks in advance!

#2

This forum is about Mongoose OS - an IoT Firmware Development Framework

closed #3