Just trying to figure out some questions.
context: randomFunction is a function that takes 2 arguments(id & metaData). It is a called inside a controller . The code is given below:
await randomFunction(id, doc);
doc contains a object (basically a document in mongodb). suppose doc contains the following:
{ _id: "123456789012345678901234", age: 30, name: 'Lorem Ipsum', gender: 'male' }
Now , in the operations file where the randomFunction is initialized.
const randomFunction = async (id, metaData) => { console.log(metaData) // prints metaData delete metaData._id console.log(metaData) // still prints metaData without deleting _id property //code below }
context: I wanted to delete the _id property of MetaData to pass it to the findOneAndUpdate() function in mongooose. But I was not able to succeed in deleting _id property. So I created the data object and passed it.
const randomFunction = async (id, metaData) => { const data = { name: metaData.name, age: metaData.age, gender: metaData.gender } //code below }
It worked.
I then tested and console logged a few things.
const randomFunction = async (id, metaData) => { console.log(metaData) // prints metaData delete metaData._id console.log(metaData) // still prints metaData without deleting _id property const data = { _id: metaData._id, name: metaData.name, age: metaData.age, gender: metaData.gender } console.log(data) // prints data object delete data._id console.log(data) // prints data with deleting _id property //code below }
So , What is the reason I was not able to delete _id in MetaData but able to able _id in Data.
When I was trying to reproduce the same thing in javascript console(chrome), I was not able to reproduce. (it is deleting the properties from arguments also.).
Advertisement
Answer
Maybe someone will find it useful.
The answer is the mongoose documents are immutable.
We need to convert the mongoose object to the javascript object.
The reason is as follows:
Link to appropriate question and answer: