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

How to use mongoose to connect to mongoDB in Ubuntu 19.10

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

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

This article shows you how to use mongoose to connect to mongoDB in Ubuntu 19.10. the content is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

Mongoose is an ODM (object data Modeling) library based on the MongoDB driver. It allows concise interaction and simple object modeling with MongoDB in a NodeJS environment.

Before you begin, it is recommended that:

Sets a non-root user with sudo privileges.

Verify that your server is up to date.

Make sure build-essential is installed. If not, the installation uses:

$sudo apt install build-essential

Step 1:MongoDB

Install MongoDB

$sudo apt install mongodb

Check that the installation is correct. Look for "active (running)" in the output.

$sudo systemctl status mongodbActive: active (running)

Steps 2:NodeJS and NPM

Add the latest stable NodeJS library.

$curl-sL https://deb.nodesource.com/setup_12.x | sudo-E bash-

Install NodeJS

$sudo apt install nodejs

Check that NodeJS and NPM are installed correctly.

$node-v & & npm-vv12.x.x6.x.x

Step 3: initialize the Mongoose project

Create the project root directory.

$cd ~ $mkdir mongooseProject & & cd mongooseProject

Initialize a NodeJS development environment and automatically generate a package.json:

$npm init

Answer short questions according to your project. For example, if you press return to accept the default value on each question, the npm init process responds:

About to write to / root/mongooseProject/package.json:

{"name": "mongooseproject", "version": "1.0.0", "description": "", "main": "index.js", "scripts": {"test": "echo\" Error: no test specified\ "& exit 1"}, "author": "", "license": "ISC"}

Use npm to install the required packages in the project root:

$npm install-save mongoose

Step 4: define a model

Create a folder called Models in the project root directory and put cd in it:

$cd ~ / mongooseProject$ mkdir Models & & cd Models

Create a connectDB.js. This file will contain the connection logic required by the MongoDB server.

$nano connectDB.js

Paste the following into connectDB.js.

Const mongoose = require ('mongoose'); / / Import mongoose library

Module.exports = function (uri) {mongoose.connect (uri, {/ / attempt to connect to database useNewUrlParser: true, / / Recommended, insures support for future MongoDB drivers useUnifiedTopology: true / / Recommended, uses new MongoDB topology engine}) .catch (error = > console.log (error)) / / Error handling

Mongoose.connection.on ('connected', function () {/ / On connection console.log (' Successful connection with database:'+ uri); / / Callback for successful connection});}

Create a Users.js. This file will contain the model of the database collection user.

$nano Users.js

Paste the following into Users.js. This defines a basic pattern for the user.

Const mongoose = require ("mongoose"); / / Import mongoose libraryconst Schema = mongoose.Schema / / Define Schema method

/ / Schemavar UsersSchema = new Schema ({/ Create Schema name: String, / / Name of user age: Number, / / Age of user role: String / / Role of user})

/ / Modelvar Users = mongoose.model ("Users", UsersSchema) / / Create collection model from schemamodule.exports = Users / / export model

Step 5: insert the document into the MongoDB

Create an insertUser.js in the root directory of the project.

$cd ~ / mongooseProject$ nano insertUser.js

Paste the following into the insertUser.js file. This file inserts the document into the user collection.

/ / Libraryconst mongoose = require ("mongoose")

/ / Database connectionconst connectDB = require (". / Models/connectDB") var database = "mongoose" / / Database name

/ / Modelsconst Users = require (". / Models/Users")

/ / Connect to databaseconnectDB ("mongodb://localhost:27017/" + database)

Var insertedUser = new Users ({/ / Create new document name: "John Doe", age: 18, role: "Example User"})

InsertedUser.save (err = > {/ / save document inside Users collection if (err) throw err / / error handling console.log ("Document inserted!") Mongoose.disconnect () / / disconnect connection from database once document is saved})

Run insertUser.js

$node insertUser.jsSuccessful connection with database: mongodb://localhost:27017/mongooseDocument inserted!

Step 6: read the document from MongoDB

Create a readUsers.js in the root directory of the project.

$cd ~ / mongooseProject$ nano readUsers.js

Paste the following into readUsers.js. This file reads the documents in the user collection.

/ / Libraryconst mongoose = require ("mongoose")

/ / Database connectionconst connectDB = require (". / Models/connectDB") var database = "mongoose" / / Database name

/ / Modelsconst Users = require (". / Models/Users")

/ / Connect to databaseconnectDB ("mongodb://localhost:27017/" + database)

Users.find ({}, (err, users) = > {/ / find and return all documents inside Users collection if (err) throw err / / error handling console.log (users) mongoose.disconnect ()})

The output of running readUsers.js is an array of objects.

$node readUsers.jsSuccessful connection with database: mongodb://localhost:27017/mongoose [{_ id: *, name: 'John Doe', age: 18, role:' Example User', _ v: 0}]

Done.

The above is how to use mongoose to connect to mongoDB in Ubuntu 19.10. have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

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

Servers

Wechat

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

12
Report