Mongooose query where ObjectId is null?

How can I find the document executing .findOne

where the field is not specified ObjectId

? I can't seem to find if I should be looking in 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 hasn't been set yet:

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 }
});

      

Again, can the field ObjectId

be null? Should I be using it String

here?

+3


source to share


1 answer


A little about undefined

in the context of MongoDB

Properties with a value are undefined

not saved. So the next property a

won't

db.insert({a : undefined})

      

However, for arrays, the values ​​are undefined

converted tonull

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

      

Also undefined

has strange behavior 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 using it undefined

and probably pretend it doesn't even exist. Use instead null

as it is stored and sometimes cannot be dropped as a condition.

So for example

db.users.insert({email : "email@domain.com", userID : null});
db.users.findOne({email : "email@domain.com", userID : null});

      

If you choose to use undefined, but do it like this

db.users.insert({email : "email@domain.com"});
db.users.findOne({email : "email@domain.com", userID : { exists : false }}); //works for null as well

      

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

+4


source







All Articles