Kevin Dario Agudelo
Kevin Dario Agudelo

Reputation: 1

How can transform the model to different responses in Mongoose

I'm making my schema and my model with Mongoose, and I need to return specific information to different endpoints in my app, something like this (A simplified example of my code)

This is my schema:

const userSchema = new mongoose.Schema({
  idNumber: Number,
  name: String,
  lastName: String,
  city: String,
  age: Number
});

And this is my model:

const User = mongoose.model('User', userSchema);

Now, I want to return specific info of my Model, something like this

router.get('/:id/getJustName', (req, res, next) => {
    User.find({ idName: req.params.id }, (err, user) => {
        //I want just return the property Name, without _id, __v, lastName, ...
    })
});

router.get('/:id/getJustCity', (req, res, next) => {
    User.find({ idName: req.params.id }, (err, user) => {
        //I want just return the property City, without _id, __v, lastName, ...
    })
});

I know that I can return something like user.city and make a delete for _id, __v and the other properties Im not need, But my application is increasing a lot, and this way to make this is not maintainable. I guest I can make somethig like transform in another schema, but I've found anything related with this :(

Thanks for helping me, Im stuck for a long time in this issue.

----- Edit 1 -----

I tried to add my own transform in schema definition but it didn't work :(

I tried this:

const userSchema = new mongoose.Schema(/path/of/my/schema, {
  toObject: {
    transform: function (doc, ret) {
      delete ret._id;
    }
  },
  toJSON: {
    transform: function (doc, ret) {
      delete ret._id;
    }
  },
  toReturnSpecificInfo: {
    transform: function (doc, ret) {
      delete ret._id;
      delete ret.lastName;
    }
  }
});

When I call

User.find((err, users) => {
  console.log(users[0].toJSON()); // This works
  console.log(users[0].toReturnSpecificInfo()); // This is Not working
})

Upvotes: 0

Views: 275

Answers (1)

Vishwak
Vishwak

Reputation: 323

You could use async/await and do the following:

router.get('/:id/getJustName', async (req, res) => {
    await User.find({ idName: req.params.id }).select({"name": 1, "_id": 0})
});

Similarly for the other query, you could do:

router.get('/:id/getJustCity', async (req, res) => {
    await User.find({ idName: req.params.id }).select({"city": 1, "_id": 0})
});

Upvotes: 2

Related Questions