Skip to content
Advertisement

Mongo shell query is not working on mongoose

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

db.userworks.aggregate([
    {
      $match: {
        user: ObjectId("607dfc9fd1ae095014ab57a0"),
        workspace: ObjectId("607dfca7d1ae095014ab57a1"),
      },
    },
    {
      $project: {
        _id: 0,
      },
    },
    {
      $lookup: {
        from: 'workspaces',
        localField: 'workspace',
        foreignField: '_id',
        as: 'workspaces',
      },
    },
    {
      $unwind: '$workspaces',
    },
    {
      $lookup: {
        from: 'projects',
        localField: 'workspaces.projects',
        foreignField: '_id',
        as: 'projects',
      },
    },
    {
      $unwind: '$projects',
    },
    {
      $project: {
        projects: 1,
      },
    },
    { $replaceRoot: { newRoot: '$projects' } },
    {
      $sort: {
        'projects.createdAt': -1,
      },
    },
  ]).pretty()

But when I run the same query using mongoose in one of my routes.

Mongoose :

const projects = await UserWorks.aggregate([
    {
      $match: {
        user: '607dfc9fd1ae095014ab57a0',
        workspace: '607dfca7d1ae095014ab57a1',
      },
    },
    {
      $project: {
        _id: 0,
      },
    },
    {
      $lookup: {
        from: 'workspaces',
        localField: 'workspace',
        foreignField: '_id',
        as: 'workspaces',
      },
    },
    {
      $unwind: '$workspaces',
    },
    {
      $lookup: {
        from: 'projects',
        localField: 'workspaces.projects',
        foreignField: '_id',
        as: 'projects',
      },
    },
    {
      $unwind: '$projects',
    },
    {
      $project: {
        projects: 1,
      },
    },
    { $replaceRoot: { newRoot: '$projects' } },
    {
      $sort: {
        'projects.createdAt': -1,
      },
    },
  ])

I would really appreciate if someone could help me with this. Because it took me a while to make this query on shell.

Answer

You can’t compare ObjectId and String.

you have to convert it ObjectId

mongoose.Types.ObjectId('607dfc9fd1ae095014ab57a0')

{
  $match: {
    user: mongoose.Types.ObjectId('607dfc9fd1ae095014ab57a0') ,
    workspace: mongoose.Types.ObjectId('607dfca7d1ae095014ab57a1'),
  },
},
Advertisement