The MJ
The MJ

Reputation: 473

only return _id from mongoose.find

want to fetch all users but just return list of _ids , checked the saved data in db everything seems good.

this is the user model

let UserSchema = new mongoose.Schema({
  firstName: {
    type: String,
    minlength: 3,
    trim: true,
  },
  lastName: {
    type: String,
    minlength: 3,
    trim: true,
  },
  biography: {
    type: String,
    minlength: 5,
    trim: true,
  },
    });

 UserSchema.methods.toJSON = function () {
   let user = this;
   let userObject = user.toObject();

   return _.pick(userObject, ["_id", "firstName", "email"]);
 };

and this is my controller function

const controller = {
    fetchUsers :async (_req, res) => {
        try {
            await User.find({})
            .then((users) => {
              res.status(200).send(users);
            })
            .catch((err) => {
              res.status(400).send(err);
            });
        } catch (error) {
          res.status(400).json({
            Error: `something is wrong. ${error}`,
          });
        }
      }
}

the result is that i tested in postman is :

[
    {
        "_id": "5fe26ba0d290a216c0fe6d5d"
    },
    {
        "_id": "5fe26c8e40ca9a06b8c96259"
    },  
 
]

Upvotes: 1

Views: 458

Answers (2)

The MJ
The MJ

Reputation: 473

problem is UserSchema.methods.toJSON method there isn't any email field, if we want to filter our output data it's better to filter it by mongoose.find({"condition"},{"fields"})

Upvotes: 1

Rupjyoti
Rupjyoti

Reputation: 399

Don't use .then & await both . Try this once. Assuming model is correct.

const controller = {
    fetchUsers :async (_req, res) => {
        try {
            const users=await User.find({}).exec()
            if(users){
              res.status(200).send(users);
            }
            else{
              res.status(404).send("no user found");
            };
        } catch (error) {
          res.status(500).json({
            Error: `something is wrong. ${error}`,
          });
        }
      }
}

Upvotes: 1

Related Questions