Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何重命名mongodb响应密钥?_Javascript_Node.js_Mongodb - Fatal编程技术网

Javascript 如何重命名mongodb响应密钥?

Javascript 如何重命名mongodb响应密钥?,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,我有以下代码: // get a specific question app.get('/:id', (req, res) => { Question.findById(req.params.id, function(err, response){ if (err) { return res.status(404).send(); } console.log(response); res.sen

我有以下代码:

// get a specific question
app.get('/:id', (req, res) => {
    Question.findById(req.params.id, function(err, response){
        if (err) {
            return res.status(404).send();
        }
        console.log(response);
        res.send(response);
    });
});
答复是:

{ 
    _id: '5b9cee54a05caf7c847aee79',
    title: 'How to make a burger?',
    description:'I wanna know the steps that i need to follow...?',
    answers: 0 
}
在将其发送给客户端之前,我希望将响应中的名称
\u id
更改为
id
,即我希望响应为:

{ 
    id: '5b9cee54a05caf7c847aee79',
    title: 'How to make a burger?',
    description:'I wanna know the steps that i need to follow...?',
    answers: 0 
}

如何做到这一点?

您想重命名json密钥吗

IE:
\u id
id

有很多方法可以做到这一点

示例1:字符串基编辑

var json=[{“_id”:“5b9cee54a05caf7c847aee79”,“标题”:“如何制作汉堡?”,“描述”:“我想知道我需要遵循的步骤…”,“答案”:“0”}];
log('Old:'+JSON.stringify(JSON));
json=json.parse(json.stringify(json).split(“_id”:”).join(““id”:”);

log('New:'+JSON.stringify(JSON))获取JSON后,解析它,以便访问属性,只需在对象上创建新属性
id
,并为其分配
\u id
的值。然后
删除
\u id
并传递JSON(再次字符串化后,取决于接收者的期望)

一些代码:

const data = JSON.parse(responseJson)
data.id = data._id
delete data._id
const fixedData = JSON.stringify(data)
如果您可以访问JS的最新功能,还可以删除不需要的
\u id
,如下所示:

const data = JSON.parse(responseJson)`
fixedData = JSON.stringify({
  ...data,
  id: data._id,
  _id: undefined
})

您可以在MongoDB中使用Aggregate

db.getCollection('Question').aggregate([{
    $match : {
         "_id" : req.params.id
    }
    },{
    $project : {
        id : '$_id',
        _id : 0, //if not required
        title: 1
        description:1
        answers:1

        }
    } 
    ])

您真正需要做的就是创建一个新的
id
属性,然后删除旧的
\u id
属性,如下所示:

// get a specific question
app.get('/:id', (req, res) => {
    Question.findById(req.params.id, function(err, response){
        if (err) {
            return res.status(404).send();
        }
        console.log(response);

        // ---
        response.id = response._id;
        delete response._id;
        // ---

        res.send(response);
    });
});

这是什么寄来的?不是数据库,而是后端?另外,您尝试过什么吗?没有@Kirk Larkin,id属性没有添加到响应中。