Being new to NoSQL / MongoDB I wonder how I can get a specific object from a potentially big document.
A document inside of my project collection looks like this:
{
"_id" : ObjectId("5935a41f12f3fac949a5f925"),
"project_id" : 13,
"updated_at" : ISODate("2017-06-28T01:43:50.994Z"),
"created_at" : ISODate("2017-06-05T18:34:07.150Z"),
"owner" : ObjectId("591eea4439e1ce33b47e73c3"),
"name" : "My demo project 1",
"visibility" : 0,
"uploaded_files" : [
{
"fieldname" : "sourceStrings",
"originalname" : "Log_20-6-2017_19-03-24-626.txt",
"encoding" : "7bit",
"mimetype" : "text/plain",
"_id" : ObjectId("5952deb44fb371d8bc00dd43")
}]
}
Instead of just one "uploaded file object" there may be hundreds. I need to get the project information (like owner, visibility, name and so on) and then I want to get the uploaded_file object by it's _id
. Obviously I could iterate through all objects inside of uploaded_files but I assume that this is performance wise horrible. What I've got so far is:
var projectId = req.params.projectId
var fileId = req.body.fileId
Project.findOne({ project_id: projectId }).populate('owner').then(project => {
if (!project)
return res.send(404, { error: "Couldn't find a project with this id"
// Here I want to get the uploaded_file object
})
My question:
- So how can I efficiently fetch a single object from the
uploaded_files
array by it's_id
field? - I need that behaviour for two cases, first is that I need to delete/modify the uploaded file or I want to get all it's information.
Is there a better database/document design for what I am trying to achieve?