showing results for - "mongoose model functions"
Marouane
13 May 2017
1// Define a `Person` model. Schema has 2 custom getters and a `fullName`
2// virtual. Neither the getters nor the virtuals will run if lean is enabled.
3const personSchema = new mongoose.Schema({
4  firstName: {
5    type: String,
6    get: capitalizeFirstLetter
7  },
8  lastName: {
9    type: String,
10    get: capitalizeFirstLetter
11  }
12});
13personSchema.virtual('fullName').get(function() {
14  return `${this.firstName} ${this.lastName}`;
15});
16function capitalizeFirstLetter(v) {
17  // Convert 'bob' -> 'Bob'
18  return v.charAt(0).toUpperCase() + v.substr(1);
19}
20const Person = mongoose.model('Person', personSchema);
21
22// Create a doc and load it as a lean doc
23await Person.create({ firstName: 'benjamin', lastName: 'sisko' });
24const normalDoc = await Person.findOne();
25const leanDoc = await Person.findOne().lean();
26
27normalDoc.fullName; // 'Benjamin Sisko'
28normalDoc.firstName; // 'Benjamin', because of `capitalizeFirstLetter()`
29normalDoc.lastName; // 'Sisko', because of `capitalizeFirstLetter()`
30
31leanDoc.fullName; // undefined
32leanDoc.firstName; // 'benjamin', custom getter doesn't run
33leanDoc.lastName; // 'sisko', custom getter doesn't run