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属性没有添加到响应中。