【问题标题】:javascript object array is not changed [duplicate]javascript对象数组未更改[重复]
【发布时间】:2017-09-02 10:28:45
【问题描述】:

这段代码是关于从 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 } ] 
     */

但这段代码可以按我的意愿工作

        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
        });
    }
});

});

我认为这与深浅复制有关。 但我不知道究竟是什么原因造成的。

谢谢

【问题讨论】:

    标签: javascript node.js mongodb copy


    【解决方案1】:

    那是因为Post.find 根据创建的 Schema 返回 mongoose 对象。您正在寻找的是返回纯 javascript 对象的 toObject 函数。 所以在你的回拨电话list.toObject(); 您可以在 mongoose 的文档中了解更多关于 toObject 函数的信息:http://mongoosejs.com/docs/api.html#document_Document-toObject

    或者,您可以使用精益选项告诉猫鼬返回纯 javascript 对象: http://mongoosejs.com/docs/api.html#query_Query-lean

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      相关资源
      最近更新 更多