use*_*211 5 javascript copy mongodb node.js
此代码用于从MongoDB获取数据并将"_id"元素更改为"id元素".但我发现对象数组没有改变.
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 } ]
*/
Run Code Online (Sandbox Code Playgroud)
但是这段代码就像我想要的那样
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
});
}
});
Run Code Online (Sandbox Code Playgroud)
});
我认为这与深层和浅层复制有关.但我不知道是什么原因引起的.
谢谢
那是因为Post.find根据创建的架构返回猫鼬对象。您正在寻找的是toObject返回纯 javascript 对象的函数。因此,在回调调用中,list.toObject();
您可以toObject在 mongoose 文档中阅读有关函数的更多信息:http://mongoosejs.com/docs/api.html#document_Document-toObject
或者,您可以使用lean选项,它会告诉mongoose返回纯javascript对象: http://mongoosejs.com/docs/api.html#query_Query-lean