TransWikia.com

Mongoose : find document with subdocument filter

Stack Overflow Asked by temp_user on January 25, 2021

I have an User like so the id is NOT the _id)

{
  id: string;
}

Which can create files like so

{
  name: string;
  author: User;
}

I would like to get all Files where the author is a given User, but I do not know how to use the "filter" function to do that.

So currently I do

const author = await this.userModel.find({ id });
return this.filesModel.find({ author });

Is there a more efficient way to do it ?

(I use NestJS with the Mongoose integration, the syntax used is the same as the Mongoose library)

EDIT

Given the User document

{
  _id: 'OVZVIbovibiugb44'
  id: 10
}

And the Files documents

[
  { name: "1.docx", author: ObjectId('OVZVIbovibiugb44') },
  { name: "2.docx", author: ObjectId('voisbvOVISBEIVBv') },
]

I would like to use the function

findOwned(authorId = 10) {
  const author = await this.userModel.find({ id });
  return this.filesModel.find({ author });
  // But do it only with "filesModel"
}

And get, as a result,

[
  { name: '1.docx', author: 'ObjectId('OVZVIbovibiugb44') },
]

One Answer

You can use $lookup into an aggregation query to merge collections.

Also, as your id is an String and your author is an ObjectId you will need one previous stage using $toObjectId

So the query is similar to this:

  • $match stage (optional) to query only with documents you want. Like a filter
  • $project to convert id String field to ObjectId. You can user $set also.
  • $lookup to merge collection and the ouput is in a field called files.
  • $project to output only files array from the merge.
db.User.aggregate([
  { "$match": { "id": "5a934e000102030405000001" } },
  { "$project": { "id": { "$toObjectId": "$id" } } },
  { "$lookup": {
      "from": "Files",
      "localField": "id",
      "foreignField": "author",
      "as": "files" }
  },
  { "$project": { "files": 1 } }
])

Example here

Correct answer by J.F. on January 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP