Q. Mongoose
MongoDB object modeling for node.js
Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in type casting, validation, query building, business logic hooks and more, out of the box.
Q. Defining your schema
Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.
var kittySchema = mongoose.Schema({
name: String,
gender: String,
birth: Date,
age: Number,
hidden: Boolean
});
Schemas not only define the structure of your document and casting of properties, they also define document
instance methods, static Model methods, compound indexes and document lifecycle hooks called middleware
Q. The Permitted Schema Types
- String
- Number
- Date
- Buffer
- Boolean
- Mixed
- ObjectId
- Array
Q. Instance methods
Instances of Models are documents. Documents have many of their own built-in instance methods. We may also define our own custom document instance methods too.
Note: methods must be added to the schema before compiling it with mongoose.model()
kittySchema.methods.speak = function () {
var greeting = this.name
? "Meow name is " + this.name
: "I don't have a name";
console.log(greeting);
}
Q. Static model methods, Query Helpers, Indexes, Virtuals
<TODO ...>
Q. Creating a model
To use our shcema definition, we need to convert our kittySchema
into a Model we can work with.
To do so, we pass it into mongoose.model(modelName, schema);
Creating a model called Kitten
var Kitten = mongoose.model('Kitten', kittySchema);
Creating Kitten instances (documents)
var silence = new Kitten({ name: 'Silence' });
var fluffy = new Kitten({ name: 'fluffy' });
console.log(silence.name); // 'Silence'
All of our Kitten instances have a speak() method available to it.
fluffy.speak(); // "Meow name is fluffy"
Q. Operations
Each document can be saved to the database by calling its save method
fluffy.save(function (err, fluffy) {
if (err) return console.error(err);
fluffy.speak();
});
Mongoose supports MongoDBs rich querying syntax.
Kitten.findOne({ name: /^fluf/ }, function(err, akitten) {
if (err) return handleError(err);
console.log('Kitten [ %s ] has found in DB', akitten.name)
});
Q. Misc
If the Node process ends, close the Mongoose connection
process.on('SIGINT', function() {
mongoose.connection.close(function () {
console.log('Mongoose disconnected on app termination');
process.exit(0);
});
});