on
Italy
- Get link
- X
- Other Apps
If you are interested in receiving more updates on Node.js and MongoDB tutorials, please subscribe here.
npm install mongoose and then import the mongoose API package in your node.js application by using the following command: var mongoose = require('mongoose');var dbHost = 'mongodb://localhost:27017/test'; mongoose.connect(dbHost);
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function(){
console.log("Connected to DB");
//do operations which involve interacting with DB.
});
//Create a schema for Book
var bookSchema = mongoose.Schema({
name: String,
//Also creating index on field isbn
isbn: {type: String, index: true},
author: String,
pages: Number
});
//Create a Model by using the schema defined above
//Optionally one can provide the name of collection where the instances
//of this model get stored. In this case it is "mongoose_demo". Skipping
//this value defaults the name of the collection to plural of model name i.e books.
var Book = mongoose.model('Book', bookSchema, "mongoose_demo");
save method on the instance to save the data to the DB. While invoking the save
method we also provide a callback which gets executed after the save
method returns either with an error or after successfully inserting the
data. The below code creates two instances of Book model class and saves
it to the DB. //Instantiating the Model - An instance of Model represents a mongodb document
var book1 = new Book({
name:"Mongoose Demo 1",
isbn: "MNG123",
author: "Author1, Author2",
pages: 123
});
//Saving the model instance to the DB
book1.save(function(err){
if ( err ) throw err;
console.log("Book Saved Successfully");
});
var book2 = new Book({
name:"Mongoose Demo 2",
isbn: "MNG124",
author: "Author2, Author3",
pages: 90
});
book2.save(function(err){
if ( err ) throw err;
console.log("Book Saved Successfully");
});
find API to query the collection. The below code defines a function which queries for documents having less than 100 pages:var queryBooks = function(){
//Now querying those books which have less than 100 pages
//Find API takes in a query condition, attributes in the document to be projected,
//callback to be executed when the data is available.
Book.find({pages : {$lt:100}}, "name isbn author pages", function(err, result){
if ( err ) throw err;
console.log("Find Operations: " + result);
});
}
update API as shown below:var updateBook = function(){
/*
Find the book to be updated using the condition and then execute the update
passed to the API as the second argument
*/
Book.update({isbn : {$eq: 'MNG125'}}, {$set: {name: "Mongoose Demo 3.1"}}, function(err, result){
console.log("Updated successfully");
console.log(result);
});
}
remove API and by specifying the condition for selecting the documents to be deleted.var deleteBook = function(){
/*
When callback is not passed, the action is not invoked on the collection
until the exec() method is called.
In this case I am not passing the callback and instead executing the action
by invoking the exec() method.
*/
Book.remove({isbn:{$eq: 'MNG124'}}).exec();
}
var mongoose = require('mongoose');
var dbHost = 'mongodb://localhost:27017/test';
mongoose.connect(dbHost);
//Create a schema for Book
var bookSchema = mongoose.Schema({
name: String,
//Also creating index on field isbn
isbn: {type: String, index: true},
author: String,
pages: Number
});
//Create a Model by using the schema defined above
//Optionally one can provide the name of collection where the instances
//of this model get stored. In this case it is "mongoose_demo". Skipping
//this value defaults the name of the collection to plural of model name i.e books.
var Book = mongoose.model('Book', bookSchema, "mongoose_demo");
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function(){
console.log("Connected to DB");
//Instantiating the Model - An instance of Model represents a mongodb document
var book1 = new Book({
name:"Mongoose Demo 1",
isbn: "MNG123",
author: "Author1, Author2",
pages: 123
});
//Saving the model instance to the DB
book1.save(function(err){
if ( err ) throw err;
console.log("Book Saved Successfully");
});
var book2 = new Book({
name:"Mongoose Demo 2",
isbn: "MNG124",
author: "Author2, Author3",
pages: 90
});
book2.save(function(err){
if ( err ) throw err;
console.log("Book Saved Successfully");
deleteBook();
});
var book3 = new Book({
name:"Mongoose Demo 3",
isbn: "MNG125",
author: "Author2, Author4",
pages: 80
});
book3.save(function(err){
if ( err ) throw err;
console.log("Book Saved Successfully");
queryBooks();
updateBook();
});
});
var queryBooks = function(){
//Now querying those books which have less than 100 pages
//Find API takes in a query condition, attributes in the document to be projected,
//callback to be executed when the data is available.
Book.find({pages : {$lt:100}}, "name isbn author pages", function(err, result){
if ( err ) throw err;
console.log("Find Operations: " + result);
});
}
var updateBook = function(){
/*
Find the book to be updated using the condition and then execute the update
passed to the API as the second argument
*/
Book.update({isbn : {$eq: 'MNG125'}}, {$set: {name: "Mongoose Demo 3.1"}}, function(err, result){
console.log("Updated successfully");
console.log(result);
});
}
var deleteBook = function(){
/*
When callback is not passed, the action is not invoked on the collection
until the exec() method is called.
In this case I am not passing the callback and instead executing the action
by invoking the exec() method.
*/
Book.remove({isbn:{$eq: 'MNG124'}}).exec();
}
> db.mongoose_demo.find()
{ "_id" : ObjectId("55490d87e34c8acc20b5363d"), "name" : "Mongoose Demo 1", "isbn" : "MNG123", "author" : "Author1, Author2", "pages" : 123, "__v" : 0 }
{ "_id" : ObjectId("55490d87e34c8acc20b5363f"), "name" : "Mongoose Demo 3.1", "isbn" : "MNG125", "author" : "Author2, Author4", "pages" : 80, "__v" : 0 }
Comments
Post a Comment