node.js - javascript object array is not changed -
this question has answer here:
- how turn mongoose document plain object? 4 answers
this code fetching data mongodb , changing '_id' element 'id element. found object array not changed.
router.get('/loadlist', (req,res) => { post.find({}, (err, list) => { //fetching data list if(err) { return res.json({success : false}); } else { let new_list; //change _id id new_list = list.map((obj) => { obj.id = obj._id; delete obj._id; return obj; }); console.log(new_list); /* // _id still here , id 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 code work 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 deleted , id 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 related deep , shallow copy. don't know cause exactly.
thanks
that's because post.find
returns mongoose object based on created schema. looking toobject
function returns pure javascript object. in callback call list.toobject();
can read more toobject
function in mongoose's documentation: http://mongoosejs.com/docs/api.html#document_document-toobject
alternatively, can use lean option tell mongoose return pure javascript object: http://mongoosejs.com/docs/api.html#query_query-lean
Comments
Post a Comment