'How to find a match that the given id matches with the document that consist it in its an array of Id
I am using mongodb. I would like to get back all documents, which consist of an array of id, that match with my ID provided.
This is the scheme of my Doc. It represents a "Post". In its "likeBy" field, this contains all the users who liked the post before.
Given that I have a user' ID, with this DB, I would like to get back all Doc in which this ID have liked before
In mongo shell, this can be done by find {likeBy:ObjectId('61eebfa4742ee001699cb504')}
But with mongoose, nothing has return.
This is what I have tried
const ObjectId = require("mongodb").ObjectId;
Post.aggregate([
{
$match: { likeBy: ObjectId(userId) }
}
])
.then((posts) => res.send(posts))
.catch((error) => {
console.log(error);
res.sendStatus(400);
});
Solution 1:[1]
import { Types } from 'mongoose';
Post.aggregate([
{
$match: { likeBy: Types.ObjectId(userId) }
}
])
.then((posts) => res.send(posts))
.catch((error) => {
console.log(error);
res.sendStatus(400);
});
when you use mongoose you have to use its own default types
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marco Bertelli |

