Home > Blockchain >  How change name of parameter on express response
How change name of parameter on express response

Time:09-27

I'm using mongoose and I would like that when I get all users send me uid instead of _id.

 const allUssers = (req, res, next) => {
  try {
    User.find({})
      .select("username")
      .select("email")
      .select("image")
      .exec((err, users) => {
        if (err) {
          return res.status(400).json({
            ok: false,
            msg: "Error listing users",
          });
        }

        return res.status(200).json({
          ok: true,
          users: users,
        });
      });
  } catch (err) {
    return res.status(500).json({
      ok: false,
      msg: "Please contact with administrator",
    });
  }
};

CodePudding user response:

You can update your schema to use an alias:

let User = new Schema({
    _id: { type: String, alias: "uid" }
});

Or you can map your users to something different:

return res.status(200).json({
  ok: true,
  users: users.map(({ _id, ...user }) => ({ uid: _id, ...user }),
});
  • Related