如何重命名mongodb响应键?

时间:2018-09-15 12:28:23

标签: 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.send(response);
    });
});

响应为:

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

在发送给客户端之前,我想在响应中将名称_id更改为id,即,我希望响应为:

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

如何实现?

4 个答案:

答案 0 :(得分:1)

您真正需要做的就是创建一个新的 public static void insertNode(Node root,int x){ { if(root==null) { root = new Node(x); return; } Node current; Queue<Node> qq = new LinkedList<Node>(); ((LinkedList<Node>) qq).push(root); while(true){ current=qq.peek(); if(current.leftchild==null){ Node child = new Node(x); child.parent = current; current.leftchild=child; return; } else { ((LinkedList<Node>) qq).add(current.leftchild);} if(current.rightChild==null){ Node child = new Node(x); child.parent=current; current.rightChild=child; return; } else{ ((LinkedList<Node>) qq).add(current.rightChild); } ((LinkedList<Node>) qq).pop(); } } 属性,然后删除旧的id属性,如下所示:

_id

答案 1 :(得分:0)

您想重命名json键

IE:_idid

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

示例1:基于字符串的编辑

var json = [{"_id": "5b9cee54a05caf7c847aee79", "title": "How to make a burger?", "description":"I wanna know the steps that i need to follow...?", "answers": "0" }];

console.log('Old : ' + JSON.stringify(json));
            
json = JSON.parse(JSON.stringify(json).split('"_id":').join('"id":'));

console.log('New : ' + JSON.stringify(json));

示例2:对象库编辑

var json = '[{"_id": "5b9cee54a05caf7c847aee79", "title": "How to make a burger?", "description":"I wanna know the steps that i need to follow...?", "answers": "0" }]';
            
console.log('OLD : ' + json);
var obj = JSON.parse(json)[0];
obj.id = obj._id;
delete obj._id;

json = JSON.stringify([obj]);

console.log('New : ' + json);

答案 2 :(得分:0)

获取JSON时,请对其进行解析,以便可以访问属性,并只需在对象上创建新属性ReplyToActivity并为其分配值Users.ReadWriteAll。然后id _id并传递JSON(再次将其字符串化后,具体取决于接收者的期望)?

某些代码:

delete

如果您有权使用JS的最新功能,则也可以像这样删除不需要的_id

const data = JSON.parse(responseJson)
data.id = data._id
delete data._id
const fixedData = JSON.stringify(data)

答案 3 :(得分:0)

您可以在 MongoDB

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

        }
    } 
    ])