I am trying to find some documents given an array of objects and inside each object, there is an id "courseId" which will be used to find the required documents from the schema with the same id. Here is the array of objects:
courseIds = [
{"courseId":"638c139b147e2173163fd976",
"_id":"63906c07b9b09cd81e48480d"
},
{"courseId":"638c131a147e2173163fd96b",
"_id":"63908c9f1897b57aa6ece69f"
}]
and if the schema contains the following objects:
const courseSchema =
[{
"_id":"638c131a147e2173163fd96b",
"courseTitle":"Neural Networks",
"price":"5000",
"shortSummary":"Its a lovely course about NNs, Sequence Models.",
"subject":"Deep Learning"
},
{
"_id":"638c139b147e2173163fd976",
"courseTitle":"Graphics",
"price":"3000",
"shortSummary":"Its a lovely course about Projection, 2D & 3D Transformations.",
"subject":"Computer Graphics"
},
{
"_id":"638c131a147e9053163fd281",
"courseTitle":"Operating Systems",
"price":"4500",
"shortSummary":"Its a lovely course about Scheduling, learning about drivers and peripherals.",
"subject":"Hardware"
}]
What I want to do is I want to find/return only the courses from the courseSchema whose ids are present in the courseIds array, like here it would only return two courses:
{
"_id":"638c131a147e2173163fd96b",
"courseTitle":"Neural Networks",
"price":"5000",
"shortSummary":"Its a lovely course about NNs, Sequence Models.",
"subject":"Deep Learning"
},
{
"_id":"638c139b147e2173163fd976",
"courseTitle":"Graphics",
"price":"3000",
"shortSummary":"Its a lovely course about Projection, 2D & 3D Transformations.",
"subject":"Computer Graphics"
}
since their ids "_id" are present in the courseIds array ("courseId == _id").
I tried to do the following:
const docs = courseSchema.find().where('_id').in(courseIds);
and
const docs = courseSchema.find({ '_id': { $in: courseIds} });
and it always return an empty array (no matches). Why doesn't it work?
1条答案
按热度按时间t40tm48m1#
courseIds id是一个数组对象,为了使_id与数组中的$匹配,必须是only _id,如[“638 c139 b147 e2173163 fd 976”,“638 c131 a147 e2173163 fd 96 b”]。
为此,您可以从courseIds数组对象中创建另一个数组,并将其用作带有$in查询。