Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript object array is not changed [duplicate]

This code is about fetching data from MongoDB and changing '_id' element to 'id element. But I found object array 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 work as 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 it is related with deep and shallow copy. But I don't know what cause it exactly.

Thanks

like image 250
user3528211 Avatar asked Oct 29 '22 09:10

user3528211


1 Answers

That's because Post.find returns mongoose object based on created Schema. What you are looking for is toObject function that returns pure javascript object. So in your callback call list.toObject(); You can read more about toObject function in mongoose's documentation: http://mongoosejs.com/docs/api.html#document_Document-toObject

Alternatively, you can use lean option which will tell mongoose to return pure javascript object: http://mongoosejs.com/docs/api.html#query_Query-lean

like image 198
Dominik Dragičević Avatar answered Nov 15 '22 04:11

Dominik Dragičević