mongoose: Cast to ObjectId failed for value on {field_object_id: {$in:[stringId1, stringId2, []]}}
Current behavior is that if I have a schema with an array of object ids referenced to another collection:
privacy: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Category',
index: true,
required: true
// removed this line from a comment below...// default: []
}],
And I want to filter all content for my categories and the public ones, in our case content that does not have a privacy_category setting. i.e. an empty array []
We currently query that with an or query
{"$or":[
{"privacy": {"$size": 0}},
{"privacy": {"$in":["5745bdd4b896d4f4367558b4","5745bd9bb896d4f4367558b2"]}}
]}
I would love to query it by only providing an empty array [] as one the comparison options in the $in statement. Like this, which mlab has confirm is possible in mongodb
"privacy_locations":{
"$in": ["5745bdd4b896d4f4367558b4","5745bd9bb896d4f4367558b2",[]]
}
(edited later: forgot to mentioned that this query, works from the console without using mongoose)
This throw cast error
{"message":"Error in retrieving records from db.","error":{"message":"Cast to ObjectId failed for value \"[]\" at path \"privacy_locations\" for model \"Article\"","name":"CastError","stringValue":"\"[]\"","kind":"ObjectId","value":[],"path":"privacy_locations"}}
That way I can avoid the $or query statement of an empty array size: 0 and the options in the $in statement and just have one in statement.
If there is a better way, Iām open to change that as well.
I just need to say, give me the content that match these privacy settings (A, B, C) and also give me the content that does not have any privacy settings.
(mongoose version 4.13.2)
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Comments: 24 (2 by maintainers)
Commits related to this issue
- test(query): repro #5913 — committed to Automattic/mongoose by vkarpov15 6 years ago
- fix(query): allow `[]` as a value for `$in` when casting Fix #5913 — committed to Automattic/mongoose by vkarpov15 6 years ago
- fix(cast): allow `[]` as a value when casting `$nin` Fix #7806 Re: #5913 — committed to Automattic/mongoose by vkarpov15 5 years ago
What is it? O great mystery-man. I shall create your query in SO, the only place on earth you may type such a SIMPLE thing, hope is not adding an
ALL
option š