node.js - Find object inside of a big document -


this question has answer here:

being new nosql / mongodb wonder how can specific object potentially big document.

a document inside of project collection looks 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 1 "uploaded file object" there may hundreds. need project information (like owner, visibility, name , on) , want uploaded_file object it's _id. iterate through objects inside of uploaded_files assume performance wise horrible. i've got 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 project id"          // here want uploaded_file object  }) 

my question:

  1. so how can efficiently fetch single object uploaded_files array it's _id field?
  2. i need behaviour 2 cases, first need delete/modify uploaded file or want it's information.

is there better database/document design trying achieve?

you can try project needed object using "$elemmatch" following:

project.findone({ project_id: projectid } ,  {uploaded_files: {$elemmatch: {_id:  fileid}}}) 

that return array needed file object .

and related how update can try following:

project.update({ project_id: projectid , 'uploaded_files._id' :  fileid} ,  {$set : {"uploaded_files.$.originalname" : "new data"} })  //for example updating "original name" filed , on. 

and notice "$" references first item match query , should 1 due depending on "_id" property in query.

finally delete specific element form array, can try following:

project.update({ project_id: projectid },  {$pull : {"uploaded_files" : {_id:fileid}} }) 

Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -