Mongoose – Insert Document to MongoDB

Insert Document to MongoDB – To insert a single document to MongoDB, call save() method on document instance. Callback function(err, document) is an optional argument to save() method. Insertion happens asynchronously and any operations dependent on the inserted document has to happen in callback function for correctness.

In this tutorial, we shall learn how to insert a document to MongoDB Collection using Node.js Mongoose module.

Example 1 – Insert Document to MongoDB using Mongoose

Following example demonstrates saving document to collection.

node-js-mongoose.js

</>
Copy
var mongoose = require('mongoose');

// make a connection 
mongoose.connect('mongodb://localhost:27017/tutorialkart');

// get reference to database
var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));

db.once('open', function() {
	console.log("Connection Successful!");
	
	// define Schema
	var BookSchema = mongoose.Schema({
	  name: String,
	  price: Number,
	  quantity: Number
	});

	// compile schema to model
	var Book = mongoose.model('Book', BookSchema, 'bookstore');

	// a document instance
	var book1 = new Book({ name: 'Introduction to Mongoose', price: 10, quantity: 25 });

	// save model to database
	book1.save(function (err, book) {
	  if (err) return console.error(err);
	  console.log(book.name + " saved to bookstore collection.");
	});
	
});

Open a terminal or command prompt and run this script using node command as shown in the following.

$ node node-js-mongoose.js 
Connection Successful!
Introduction to Mongoose saved to bookstore collection.

Now check your MongoDB if the document is inserted.

> show collections
bookstore
customers
myNewCollection
people
stores
webpages
> db.bookstore.find()
{ "_id" : ObjectId("5a76f2616204971c6f0456f3"), "name" : "Introduction to Mongoose", "price" : 10, "quantity" : 25, "__v" : 0 }
> 

A new collection has been created (as it is not already present), and the document is inserted to the collection.

Conclusion

In this Node.js Mongoose Tutorial, we have learnt to insert document to MongoDB using Mongoose from Node.js. In our next tutorial, we shall learn to insert multiple documents to MongoDB using Mongoose.