Search code examples
mongoose

How do I add a document using mongoose with one field being empty object?


This is my schema:

const wlb_schema = new mongoose.Schema({
  wlbId: Number,
  wlbName: String,
  color: String,
  coordinates: Object,
  boardId: []
})

I want to add a document using this schema, where coordinates would be an empty object. I tried to do it like this:

  const wlb = new WLB({
    wlbId: req.body.wlbId,
    wlbName: req.body.wlbName,
    color: req.body.color,
    coordinates: {},
    boardId: req.body.boardId
  })
  wlb.save()

It didn't create coordinates key at all. So I asked AI, it told me to omit coordinates:

  const wlb = new WLB({
    wlbId: req.body.wlbId,
    wlbName: req.body.wlbName,
    color: req.body.color,
    boardId: req.body.boardId
  })
  wlb.save()

It also didn't create coordinates key at all.
I am now using a workaround:

  const wlb = new WLB({
    wlbId: req.body.wlbId,
    wlbName: req.body.wlbName,
    color: req.body.color,
    coordinates: {
      something: "i needed to insert this here"
    },
    boardId: req.body.boardId
  })
  wlb.save()

Is there a way to create coordinates as empty object? Or do I need to use this idiotic workaround?


Solution

  • Mongo does not save empty objects by default. It is done to save storage. YOu can override this behaviour by using minimize.

    const wlb_schema = new mongoose.Schema({
      wlbId: Number,
      wlbName: String,
      color: String,
      coordinates: Object,
      boardId: []
    }, { minimize: false })