In this article, we will see how to use “mongoose” to connect to “MongoDB” from Node.JS. Mongoose provides object modeling and schema for application data. Follow the below steps to work with mongoose.
Step 1: Install the “mongoose” node module dependency.
npm install mongoose --save
Step 2: Get the connection to the MongoDB.
var mongoose = require('mongoose'); var sampleMongoConnection = mongoose.createConnection('mongodb://localhost/sample_db', function(err) { if (err) { console.log("The connection to the MONGODB is failed"); } else { console.log("The connection to the MONGODB is successful !!!"); } });
Step 3: Define the mongo schema. The schema reflects the document structure in the MongoDB.
//create User schema var userSchema = new mongoose.Schema({ username: {type:String, required: true, trim: true}, password: {type:String, required: true, trim: true}, email: {type: String, required: true, trim: true}, first_name: {type:String, required: true, trim: true}, last_name: {type: String, required: true, trim: true}, gender: {type: String, required: true, trim: true}, date_of_birth: { type: Date, required: true }, created_at: { type: Date, default: Date.now }, last_modified_at: { type: Date, default: Date.now }, is_active: { type: Boolean, default: true } }, { collection: 'users'} );
The explanation of the above code is given below.
Step 4: Create a model from the userSchema created in the above step.
var User = sampleMongoConnection.model('user', userSchema);
Step 6: Now, write the code to save user data into the “users” collection.
app.get('/_createUser', function(req, res) { // create the user var newUser = new User(); newUser.username = "sample" newUser.password = "sample123"; newUser.email = "sample@gmail.com"; newUser.first_name = "sample first name"; newUser.last_name = "sample last name"; newUser.gender = "male"; newUser.date_of_birth = new Date("11/08/1984"); // save the user newUser.save(function(err) { if (err) { console.log('Error in Saving user: ' + err); res.status(500); res.send("user creation is not successful"); } else { console.log('User Registration succesful'); res.send("user creation is successful"); } }); });
The explanation of the above code is given below.
If you go to the sample_db and query the “users” collection, you are able to see the user document which we inserted in the above step.
{ "_id" : ObjectId("56234935f7564a742092814e"), "date_of_birth" : ISODate("1984-11-07T18:30:00Z"), "gender" : "male", "last_name" : "sample last name", "first_name" : "sample first name", "email" : "sample@gmail.com", "password" : "sample123", "username" : "sample", "is_active" : true, "last_modified_at" : ISODate("2015-10-18T07:24:37.032Z"), "created_at" : ISODate("2015-10-18T07:24:37.027Z"), "__v" : 0 }
In the coming article, we will discuss another node module. Till then, Stay Tune to learn Node.JS.
Leave a Reply