Ryan D'Baisse
Ryan D'Baisse

Reputation: 863

Mongooose query where ObjectId is null?

How can I search for a document doing a .findOne where an ObjectId field is not set? I cannot find if I should be searching on null or undefined or something else.

In the example below, I'm trying to find a document where the "email" value IS known but the userId has not yet been set:

var joinRequest = new mongoose.Schema({
    email: { type: String, unique: true, lowercase: true, trim: true },
    code: { type: String, uppercase: true, trim: true, select: false  },
    lastSent: { type: Date },
    userId: { type: mongoose.Schema.Types.ObjectId, select: false }
});

Then again, can an ObjectId field ever be null? Should I use a String here?

Upvotes: 3

Views: 4698

Answers (1)

Logan Murphy
Logan Murphy

Reputation: 6230

Few things about undefined in the context of MongoDB

Properties with the value undefined are not stored. So the following will have no a property

db.insert({a : undefined})

However for arrays the undefined values are converted to null

db.insert({a : [undefined]}) //stores {a : [null]}

Also undefined has weird behaviors when used as a condition

db.users.find({a : undefined}) //finds everything
db.users.findOne({a : undefined}) //always returns the first document (which is a problem for you)
db.users.update({a : undefined}, {a : true}) //only updates documents with no a property

So I would avoid the use of undefined and probably pretend it doesn't even exist. Use null instead since it is stored and does't sometimes get dropped as a condition.

So for example

db.users.insert({email : "[email protected]", userID : null});
db.users.findOne({email : "[email protected]", userID : null});

If you decide to use undefined though do it like this

db.users.insert({email : "[email protected]"});
db.users.findOne({email : "[email protected]", userID : { exists : false }}); //works for null as well

http://docs.mongodb.org/manual/reference/operator/query/exists/

Upvotes: 4

Related Questions