I have written a shell query which works perfectly on mongo shell but is not returning any value when run using mongoose in nodejs + typescript;
Mongo shell
JavaScript
x
47
47
1
db.userworks.aggregate([
2
{
3
$match: {
4
user: ObjectId("607dfc9fd1ae095014ab57a0"),
5
workspace: ObjectId("607dfca7d1ae095014ab57a1"),
6
},
7
},
8
{
9
$project: {
10
_id: 0,
11
},
12
},
13
{
14
$lookup: {
15
from: 'workspaces',
16
localField: 'workspace',
17
foreignField: '_id',
18
as: 'workspaces',
19
},
20
},
21
{
22
$unwind: '$workspaces',
23
},
24
{
25
$lookup: {
26
from: 'projects',
27
localField: 'workspaces.projects',
28
foreignField: '_id',
29
as: 'projects',
30
},
31
},
32
{
33
$unwind: '$projects',
34
},
35
{
36
$project: {
37
projects: 1,
38
},
39
},
40
{ $replaceRoot: { newRoot: '$projects' } },
41
{
42
$sort: {
43
'projects.createdAt': -1,
44
},
45
},
46
]).pretty()
47
But when I run the same query using mongoose in one of my routes.
Mongoose :
JavaScript
1
47
47
1
const projects = await UserWorks.aggregate([
2
{
3
$match: {
4
user: '607dfc9fd1ae095014ab57a0',
5
workspace: '607dfca7d1ae095014ab57a1',
6
},
7
},
8
{
9
$project: {
10
_id: 0,
11
},
12
},
13
{
14
$lookup: {
15
from: 'workspaces',
16
localField: 'workspace',
17
foreignField: '_id',
18
as: 'workspaces',
19
},
20
},
21
{
22
$unwind: '$workspaces',
23
},
24
{
25
$lookup: {
26
from: 'projects',
27
localField: 'workspaces.projects',
28
foreignField: '_id',
29
as: 'projects',
30
},
31
},
32
{
33
$unwind: '$projects',
34
},
35
{
36
$project: {
37
projects: 1,
38
},
39
},
40
{ $replaceRoot: { newRoot: '$projects' } },
41
{
42
$sort: {
43
'projects.createdAt': -1,
44
},
45
},
46
])
47
I would really appreciate if someone could help me with this. Because it took me a while to make this query on shell.
Advertisement
Answer
You can’t compare ObjectId and String.
you have to convert it ObjectId
JavaScript
1
2
1
mongoose.Types.ObjectId('607dfc9fd1ae095014ab57a0')
2
JavaScript
1
7
1
{
2
$match: {
3
user: mongoose.Types.ObjectId('607dfc9fd1ae095014ab57a0') ,
4
workspace: mongoose.Types.ObjectId('607dfca7d1ae095014ab57a1'),
5
},
6
},
7