-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodelsExample.js
More file actions
40 lines (27 loc) · 1.75 KB
/
modelsExample.js
File metadata and controls
40 lines (27 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*
In the following example, the objective is to create a model of a Car such that the schema that all documents
in our database will have will have make, model, year, and rating. We also have a virtual which can manipulate
the properties in our Schema to create specific values. Additionally, you can use an instance method if you need
to keep sensitive information from the client.
*/
const mongoose = required('mongoose'); // Import Mongoose
const carSchema = new mongoose.Schema({ // New schema of carSchema
make: String,
model: String,
year: Number,
rating: String
});
carSchema.virtual('fullCarName', function() { // If you need to manipulate the properties in your carSchema to create something new,
return `${this.make} ${this.model}`.trim(); // you simply create a virtual to, in this case, concatenate property values together.
});
carSchema.methods.serialize = function() { // If you need to keep sensitive information away from the client, you would use an
return { // instance method like this which would omit senitive information (i.e. rating).
make: String,
model: String,
year: Number
}
}
const Car = mongoose.model('Car', carSchema); // Create the "Car" model by creating a model with the collection name in
// corresponding MongoDB database (e.g. Car) and the corresponding schema (carSchema).
module.exports = { Car }; // Export the models on your page via destructured object.
// In this case, we only have one model... Car.