Reputation: 142911
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?
Upvotes: 1
Views: 690
Reputation: 311835
You've declared the language
field as an ObjectId in the schema, but in the MongoDB document it's actually a string. So in your find
call, Mongoose is going to cast the language
variable to an ObjectId and then the query will return any documents where language
is 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 language
contains an ObjectId instead of a string or change your schema so that language
is defined as type: String
. If you want to treat language
as a reference as you're doing in the schema then you'll need to do the former.
Upvotes: 2