Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Express uses Mongoose to connect MongoDB operation example [download source code]

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

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.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report