Why am I not being able to write into objects I fetched from database?

Viewed 93

What I am trying to do: I am fetching data from MongoDB(doc). I has property files which is an array of objects. Schema of the mentioned object:

{
    fileName : {type : String, required : true},
    fileSize : {type : Number, required : true},
    fileOriginalName : String,
    sentEarlier : Boolean,
  }

and before sending this array(in doc.files) to my frontend, I want to append a property(downloadLink), to each object. The whole code where I encountered the problem:

Router.post('/fetch-more-files', (req, res) => {
  let {uuid} = req.body;
  File.findOne({uuid}, (err, doc) => {
    if(err) {
      return res.send({'error' : 'Something went wrong. Refresh the page.'});
    }

    if(!doc) {
      return res.send({'error' : 'Invalid link or link expired'});
    }

    let newFiles = [];

    doc.files.forEach(file => {
      file.downloadLink = `${process.env.APP_BASE_URL}/files/download/${uuid}/${file.fileName}`;
    });

    doc.files.forEach(file => {
      if(!file.sentEarlier) newFiles.push(file);
    });

    doc.save((err, savedDoc) => {
      res.json({newFiles});
    });
  });
});

PROBLEM: The newFiles array which I am populating with all the files(objects inside doc.files array), those that do not have a 'sentEarlier' key true to them, when sent as response, not a single object that array has the 'downloadLink' property to them. I tried so hard and for so long to debug, but failed. Hope to find some insights as to what I could be doing wrong here. Thanks in advance!!!

2 Answers

SOLUTION: After hours of lingering and loitering over this problem, I found a solution. If you want the technical answer to why it didn't work, this is not the place for you. But if you just want your problem solved, so you can finally go pee, read on.

The answer is to use toObject() method which apparently converts the mongoose document to a plain JS object, which is now at your disposal.

toObject() in mongooseJS documentation:

Mongoose v5.11.9:API docs | document.prototype.toObject()

Other answers are most welcome.

Mongoose queries return an instance of the Mongoose Document class. if you want to modify your query response just try to call your mongoose query in a different way.

File.findOne({uuid}, {new: true}).lean().exec((err, doc) => {
    if(err) {
      return res.send({'error' : 'Something went wrong. Refresh the page.'});
    }
    // your logic
});

here you get more idea about lean()

Related