Array of javascript objects not changing

This code focuses on retrieving data from MongoDB and changing the _id element to id. But I found that the array of objects is not changed.

router.get('/loadList', (req,res) => { Post.find({}, (err, list) => { //fetching data to list if(err) { return res.json({success : false}); } else { let new_list; //change _id to id new_list = list.map((obj) => { obj.id = obj._id; delete obj._id; return obj; }); console.log(new_list); /* // _id is still here and id is not created [{_id: '58e65b2d1545fe14dcb7aac5', title: 'asdfassafasdf', content: 'dfasfdasdf', time: '2017-04-06T15:13:49.516Z', writer: { _id: '100975133897189074897', displayName: 'Kiyeop Yang' }, coords: { y: '310.3999786376953', x: '139' }, __v: 0 } ] */ 

but this code works like what i want

  let list2 = JSON.parse(JSON.stringify(list)); new_list = list2.map((obj) => { obj.id = obj._id; delete obj._id; return obj; }); console.log(new_list); /* // _id is deleted and id is created { title: 'asdfassafasdf', content: 'dfasfdasdf', time: '2017-04-06T15:13:49.516Z', writer: { _id: '100975133897189074897', displayName: 'Kiyeop Yang' }, coords: { y: '310.3999786376953', x: '139' }, __v: 0, id: '58e65b2d1545fe14dcb7aac5' } ] */ return res.json({ success : true, list }); } }); 

});

I think this is due to a deep and shallow copy. But I do not know what is the reason.

thanks

+5
source share
1 answer

This is because Post.find returns a mongoose object based on the generated schema. What you are looking for is a toObject function that returns a pure javascript object. Therefore, the callback to list.toObject(); You can learn more about toObject functions in the mongoose documentation: http://mongoosejs.com/docs/api.html#document_Document-toObject

Alternatively, you can use the lean option, which tells mongoose to return a clean javascript object: http://mongoosejs.com/docs/api.html#query_Query-lean

+2
source

Source: https://habr.com/ru/post/1266457/


All Articles