If I have a schema like this:
var Word = new Schema({
name: { type: String, required: true },
language: { type: ObjectId, ref: "Language", required: true }
});
and I try to query it like this
var language = "5078547df6b753bc06000003";
word.find({ language: language }, function (err, words) {
console.log(words);
});
I get an empty result set ([]). I know there exists a word with this language, because if I remove the {language: language} I get this object:
[{
"_id": "5079fd7b6df57b1b64cbf25d",
"name": "dog",
"language": "5078547df6b753bc06000003",
}]
I’ve tried using
var language = mongoose.Types.ObjectId("5078547df6b753bc06000003");
word.find({ language: language }, //etc.
but it still returns an empty result set.
Why can’t mongoose find the word with this language id?
You’ve declared the
languagefield as an ObjectId in the schema, but in the MongoDB document it’s actually a string. So in yourfindcall, Mongoose is going to cast thelanguagevariable to an ObjectId and then the query will return any documents wherelanguageis an ObjectId with that value (and won’t find any because it’s not an ObjectId in the database).You either need to update the document so that
languagecontains an ObjectId instead of a string or change your schema so thatlanguageis defined astype: String. If you want to treatlanguageas a reference as you’re doing in the schema then you’ll need to do the former.