Andre M
Andre M

Reputation: 7534

Mongoose Boolean false vs undefined?

In mongoose, what is the right way to check the field value is undefined, rather than false?

We have model, which has a Boolean property, but not be initially set. For this reason the possible values are actually: undefined | true | false. Here we need to make the distinction.

The operation is being done from with a NodeJS based application.

An example, as requested:

// Simply schema
const PreferencesSchema = new mongoose.Schema({
   forUser: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
   allowActionX: {
        type: Boolean,
        default: undefined
    }
});

const Preferences = mongoose.model<any>('Preferences', PreferencesSchema);

const preferences = Preferences.findOne({ user: user });

// if preference.allowActionX is not defined:
//   use default behaviour
// else if preference.allowActionX is true
//   do action X
// else 
//   don't do action X

Upvotes: 0

Views: 1831

Answers (1)

Lucas Hendren
Lucas Hendren

Reputation: 2826

If you want to return a document where a field exists AND is not null, use { a : {$ne: null}}

otherwise you can also check afterword with the === operator to determine if something is false vs undefined The triple equals, ===, in JavaScript, tests for strict equality. This means both the type and the value we are comparing have to be the same.

if (myvar === false) {
  //insert code
}
else if ( myvar === undefined){
  //insert code
}

https://codeburst.io/javascript-double-equals-vs-triple-equals-61d4ce5a121a

Upvotes: 1

Related Questions