Joe Beuckman Joe Beuckman - 2 months ago 7
Node.js Question

Why does this array-field query fail in Mongoose but not Mongo shell?

This is my

User
schema in Mongoose.

var userSchema = mongoose.Schema({
username: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
},
mobile: {
type: Number,
required: true
},
accounts: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Account'
}]
});

var User = mongoose.model('User', userSchema);


In mongo shell, this finds my existing user document:

db.users.find({ accounts:"57d03b30edfd30e806fb20c9"})


But with Mongoose, this finds the empty set:

User.find({ accounts: "57d03b30edfd30e806fb20c9" })
.exec(function (err, users) {

*** users == [] ***

});

Answer

actually, if the schema matches, you should just treat ObjectId as a string

accounts: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Account'
}]

then query it like it is a string

User.find({ accounts: "57d03b30edfd30e806fb20c9" })
.exec(function (err, users) {

   *** users == [] ***

});

but you need to delete the previous entry, since it is currently a "mixed" type. I am guessing mixed is really just a string, so you could try to use string type like below. well, the fact that you could query a string in mongoshell and find a result

  accounts: [{
    type: mongoose.Schema.Types.String,
    ref: 'Account'
}] 
Comments