Express uses Mongoose to connect MongoDB operation example [download source code]
This article example describes express using Mongoose to connect MongoDB operations. Share it for your reference, as follows:
Why learn Mongoose?
Mongoose is an object model tool of MongoDB, encapsulating some common methods such as adding, deleting and querying documents of MongoDB, making NodeJS operation Mongodb database more flexible and simple.
0, Install nodejs and mongoDB->MongoDB installation
1. Create Express Project
2. Enter the project directory to install mongoose and introduce dependencies:
npm install --save mongoose
3. Use mongoose to connect to mongoDB database
var express = require('express');var app = express();/** *** Official example ****//Introduction of mongoose module var mongoose = require ('mongoose ');//Create database connection var db=mongoose.connect ('mongodb://localhost:27017/test');//check if connection succeeds db.connection.on ("error",function(error){ console.log ("Database connection failed: "+error);});db.connection.on ("open",function(error){ console.log ("++++++ Database connection succeeded +++++");});//Insert data test//Create a model named Cat and specify the attribute name Stringvar Cat = mongoose.model ('Cat',{ name: String });//a kitty object var kitty = new Cat({ name: 'tinyphp' });//save a record kitty.save(function (err) { if (err) { console.log(err); } else { console.log ('successfully inserted data'); }});/** **********/module.exports = app;
4. Start mongoDB database and enter mongo command
5. Open another command window npm start to start the project
6. Verify that a record has been successfully inserted.
Actually... Here seems to have little to do with express, just install the dependency at the beginning, but sometimes it is a little bit worse, and the thinking is a lot more cheerful..
Click here to download the full source code.
I hope this article is helpful for MongoDB database programming.