Reputation: 3
I'm creating an api with node.js, express and mongoose. I'm pretty new to mongosse and I am wondering if there exists a better way to do what I want.
I have two collections: users and expenses.
User example:
{
"_id" : ObjectId("59c4bc6a39d9992d6407427e"),
"firstName" : "John",
"lastName" : "Doe",
"name" : "JohnD",
"password" : "xxxxx",
"__v" : 26,
"budget" : 400,
"saving" : 300,
"wage" : 1340,
"expenses" : [
ObjectId("59cd076544fa3e64ec32c7e3"),
ObjectId("59cd07f0ed7bd2192cab72bd"),
ObjectId("59cd0a78e19060451059dce7"),
ObjectId("59cd0b24e19060451059dce8"),
ObjectId("59cd0b8fe19060451059dce9"),
ObjectId("59cdf34be19060451059dcf4"),
ObjectId("59cdf3c1e19060451059dcf5"),
ObjectId("59cdf417e19060451059dcf6"),
ObjectId("59cdf446e19060451059dcf7"),
ObjectId("59cdf46ee19060451059dcf8"),
ObjectId("59cdf4bce19060451059dcf9"),
ObjectId("59cdf6dee19060451059dcfa"),
ObjectId("59cdf6f5e19060451059dcfb"),
ObjectId("59cdf768e19060451059dcfc"),
ObjectId("59cdf798e19060451059dcfd"),
ObjectId("59cdf806e19060451059dcfe")
]
}
Expense example:
{
"_id" : ObjectId("59cd07f0ed7bd2192cab72bd"),
"name" : "shopping",
"price" : 100,
"date" : 1506607687013,
"repetition" : 0,
"__v" : 0
}
{
"_id" : ObjectId("59cd0a78e19060451059dce7"),
"name" : "gazoil",
"price" : 50,
"date" : 1506607687013,
"repetition" : 0,
"__v" : 0
}
I want to do a function which takes a user and return all of its expenses. Am I forced to loop through all objectId in user.expenses or there is a proper way to do that directly with mongoose ?
Upvotes: 0
Views: 97
Reputation: 2921
Mongoose has a method for doing what you are willing to do: Query Population
You need to set your schema right and push the refs to the children, then use the populate()
method:
const user = await User
.findOne({ _id: 'yourObjId' })
.populate('expenses')
.exec()
console.log(user.stories)
Upvotes: 3
Reputation: 8380
You can use $lookup/aggregate
Check some examples on this answer which seem to explain your use case.
Mongodb, aggregate query with $lookup
Upvotes: 0