prabodhprakash
prabodhprakash

Reputation: 3927

Mongoose unable to get _id from Schema

I 've a UserSchema that looks like:

export var UserSchema: Schema = new mongoose.Schema({
  createdAt: Date,
  email: {
    type: String,
    required: true,
    trim: true,
    unique: false,
  },
  firstName: {
    type: String,
    required: false,
    trim: true
  },
  lastName: {
    type: String,
    required: false,
    trim: true
  },
  password: {
    type: String,
    trim: true,
    minlength: 6
  },
  tokens: [{
    access: {
      type: String,
      required: true
    },
    token: {
      type: String,
      required: true
    }
  }]
});

And I 've a instance method like:

   UserSchema.methods.printThis =  () => {
        var user = this;
        console.log("========>>> PRINTING USER NOW");
        console.log(user);
};

The method printThis is being called from

router.post('/signup', (req, res) => {
    var body = _.pick(req.body, ['email', 'password']);
    var user = new User(body);

    console.log("created user as: ", user);

    user.printThis();
});

Below is the output:

created user as:  { email: '[email protected]',
  password: '123456',
  _id: 59be50683606a91647b7a738,
  tokens: [] }
========>>> PRINTING USER NOW
{}

You can see that the user is getting created properly. However, when I call printThis method on User - I'm not able to print the same user back and an empty {} is printed. How to fix this?

Upvotes: 0

Views: 40

Answers (2)

Shaishab Roy
Shaishab Roy

Reputation: 16805

To get the _id value from the instance method can use _conditions that should work

UserSchema.methods.printThis = function(password) {
    var user = this;
    console.log(user._conditions['_id']);
};

Upvotes: 0

robertklep
robertklep

Reputation: 203494

You shouldn't use arrow functions (=>) if the calling function is explicitly setting a context (which is what Mongoose does):

UserSchema.methods.printThis = function() {
  var user = this;
  console.log("========>>> PRINTING USER NOW");
  console.log(user);
};

More info on arrow functions and their handling of this here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#Arrow_functions

Upvotes: 1

Related Questions