Models

A model in Mongoose is a class that can be instantiated (defined by a schema).
Using schemas, we define models and then use them as regular JavaScript objects.
The benefit is that the model object has the added bonus of being backed by Mongoose, so it also includes features such as saving, finding, creating, and removing. Let's take a look at defining a model using a schema and then instantiating a model and working with it. Add another file called test2.js to your experimentation folder, mongotest/test2.js, and include the following block in it:

const mongoose = require('mongoose'),
Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost:27017/mongotest');
mongoose.connection.on('open', function() {
console.log('Mongoose connected.');
});

var Account = new Schema({
username: { type: String },
date_created: { type: Date, default: Date.now },
visits: { type: Number, default: 0 },
active: { type: Boolean, default: false }
});

var AccountModel = mongoose.model('Account', Account);
var newUser = new AccountModel({ username: 'randomUser' });
console.log(newUser.username);
console.log(newUser.date_created);
console.log(newUser.visits);
console.log(newUser.active);

Running the preceding code should result in something similar to the following:

    $ node test2.js
    randomUser
    Mon Jun 02 2014 13:23:28 GMT-0400 (EDT)
    0
    false

Creating a new model is great when you're working with new documents and you want a way to create a new instance, populate its values, and then save it to the database:

var AccountModel = mongoose.model('Account', Account);
var newUser = new AccountModel({
username: 'randomUser'
});
newUser.save();

Calling .save on a mongoose model will trigger a command to MongoDB that
will perform the necessary insert or update statements to update the server. When you switch over to your mongo shell, you can see that the new user was indeed saved to the database:

> use mongotest
switched to db mongotest
> db.accounts.find()
{ "username" : "randomUser", "_id" : ObjectId("538cb4cafa7c430000070f66"), "active" : false, "visits" : 0,
"date_created" : ISODate("2014-06-02T17:30:50.330Z"), "__v" : 0 }
Without calling .save() on the model, the changes to the model won't actually be persisted to the database. Working with Mongoose models in your Node code is just that--code. You have to execute MongoDB functions on a model for any actual communication to occur with the database server.

You can use AccountModel to perform a find operation and return an array of AccountModel objects, based on some search criteria that retrieves results from the MongoDB database:

// assuming our collection has the following 4 records: 
// { username: 'randomUser1', age: 21 }
// { username: 'randomUser2', age: 25 }
// { username: 'randomUser3', age: 18 }
// { username: 'randomUser4', age: 32 }

AccountModel.find({ age: { $gt: 18, $lt: 30 } }, function(err, accounts) {
console.log(accounts.length); // => 2
console.log(accounts[0].username); // => randomUser1
mongoose.connection.close();
});

Here, we use the standard MongoDB commands $gt and $lt for the value of age when passing in our query parameter to find documents (that is, find any document where the age is above 18 and below 30). The callback function that executes after find references an accounts array, which is a collection of AccountModel objects returned from the query to MongoDB. As a general means of good housekeeping, we close the connection to the MongoDB server after we are finished.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.170.134