user3829146
user3829146

Reputation:

Mongoose - Excluding fields from returned object on .save

When I save a new user to my app's database, I need to return a user object back to the client, but there are certain fields in the user object I want excluded so the client doesn't receive them.

Currently I'm saving the document, then finding that document in the collection again, excluding some fields, then sending that.

Is it possible to exclude the fields on .save instead, saving another trip back to the database?

...

function hashing(err, hash) {
    if (err) {
        return next(err);
    }

    newUser.password = hash;
    newUser.save(saveUser);
}

function saveUser(err, user) {
    if (err) {
        return next(err);
    }

    User.findOne({ username: user.username },
    '-purchased -following -songs')
    .exec(findAndSendUser);
}

function findAndSendUser(err, user) {
    if (err) {
        return next(err);
    }

    res.send({
        success: true,
        user: user
    });
}

Upvotes: 1

Views: 3355

Answers (2)

Zeeshan Ahmad
Zeeshan Ahmad

Reputation: 5644

Use following:

let user = await UserModel.create({
  email: "[email protected]",
  password: "example"
});

user = user.toObject();

delete user.password;

console.log(user);

Output

{
  "_id": "5dd3fb12b40da214026e0658",
  "email": "[email protected]"
}

Upvotes: 1

Benoir
Benoir

Reputation: 1244

Why not just use underscore to omit certain fields from the user

_ = require('underscore');

...

function saveUser(err, user) {
    if (err) {
        return next(err);
    }
    findAndSendUser(err, _.omit(user.toJSON(), 'purchased', 'following', 'songs'));
}

Upvotes: 0

Related Questions