0

Working with a toy example, lets say I have the following Schema:

const ExampleSchema = new mongoose.Schema({
  publicField: String,
  privateField: { type: String, select: false }
});

ExampleSchema.methods.doSomething = async function() {
  console.log(this.privateField); // undefined
}

How do I access the privateField in the doSomething function?

Or is there a better to achieve this?

Krimson
  • 7,386
  • 11
  • 60
  • 97
  • Please look at this link...https://github.com/Automattic/mongoose/issues/1596 .... https://stackoverflow.com/questions/12096262/how-to-protect-the-password-field-in-mongoose-mongodb-so-it-wont-return-in-a-qu – Parth Raval Jan 08 '19 at 06:20
  • hmm makes sense. Currently, I'm using that workaround of selecting the whole object and then deleting the sensitive fields in the `.toObject()` function – Krimson Jan 08 '19 at 06:35

1 Answers1

0

The privateField is accessed correctly for doSomething instance method in your schema definition.

The ExampleSchema makes the doSomething method available on the Model using it.

this.privateField refers to the privateField property of the model instance.

Lets say there is an Example model that uses ExampleSchema definition

const Example = mongoose.model('Example', ExampleSchema);

When an instance of Example is constructed, it will have doSomething method available on it.

const example = new Example({privateField: 'This is a privateField'});
example.doSomething(); // logs "This is a privateField" 
Oluwafemi Sule
  • 36,144
  • 1
  • 56
  • 81