I have 3 schemas:
const userSchema = new mongoose.Schema({
username:{
type: String,
unique: true
},
password:{
type: String
},
tasks:{
type:[mongoose.Types.ObjectId]
}
})
const taskSchema = new mongoose.Schema({
title:{
type: String
},
finished:{
type: Boolean
},
deadline:{
type:Date
},
subtasks:{
type:[mongoose.Types.ObjectId]
}
})
const subtaskSchema = new mongoose.Schema({
title:{
type: String
},
finished:{
type: Boolean
},
deadline:{
type:Date
},
})
I would like to perform a query that would return something like this:
{
"_id": "id",
"username": "username",
"password": "password",
"tasks": [
"_id": "id",
"title": "title",
"deadline": "deadline",
"finished": false,
"subtasks": [
{
"_id": "id",
"title": "title",
"deadline": "deadline",
"finished": false
}
]
]
}
To my understading, aggregate should do this but I’m not quite sure how to handle nested arrays with it. I know that relational DBs would suit this better, but this is the situation I am currently in. Any help is appreciated!
3
Answers
I did it using the populate method as suggested
You might not need an aggregate since your user schema already has tasks as an array in them, so you could just call "populate" on the user records via mongoose. Take a look at this for example https://mongoosejs.com/docs/populate.html
in your
userSchema
, addref: 'task'
or anything you name to yourtask model
to point it in your task collection.same thing you to your
taskSchema
, addref: 'subtask'
or whatever you name in your subtask collection.with that you could your
populate
function rather thanaggregate
in that case we are have nested populate since
subtask
is a field intask