0

How not to insert empty object i.e { } in Mongoose schema.

Let suppose Mongoose collection is as follows

let testCollection = mongoose.Schema({
  someData:{
    type: []
  }

Insert in Mongoose collection is as follows

let emptyObj = { }

new testCollection({
 someData: emptyObj
}).save()

If this code executes, mongoose collection will be like this

 db.somecollection.find().pretty()

    {
     "someData" : [
       { }
      ]
    }

How to insert object in this array only if the object is not empty?

1 Answer 1

2

If there are no other fields, this can be done with a ternary:

const isEmpty = !obj || Object.keys(obj).length;

new testCollection(isEmpty ? { someData: emptyObj } : {}).save()

Otherwise this can be done with object spread and short-circuit evaluation in order to avoid repetitions and additional temporary variables:

new testCollection({
  someField: 'value',
  ...(isEmpty || { someData: emptyObj })
}).save()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.