Home  >  Article  >  Operation and Maintenance  >  How to connect Node.js program with MongoDB on CentOS and Fedora

How to connect Node.js program with MongoDB on CentOS and Fedora

不言
不言Original
2019-03-29 16:27:062919browse

This article will introduce how to connect Node.js applications to MongoDB. Also, configure MongoDB driver for nodejs using Mongoose node application on CentOS and Redhat systems.

How to connect Node.js program with MongoDB on CentOS and Fedora

Step 1: First conditions

We assume that node.js and mongodb are already installed on the system. If it is not installed, you can refer to the following article to complete the required installation.

1, How to install MongoDB on CentOS and Fedora

2, How to install Node.js on CentOS and Fedora

Step 2: Install the Mongoose module

Mongoose provides a simple schema-based solution for application data modeling, including built-in type conversion, validation, and more.

$ npm install mongoose

Step 3: Connect nodejs with mongodb

Create a test_server.js file and add the following content to the file.

// Sample script of Node.js with MongoDB Connection

// This code requires mongoose node module
var mongoose = require('mongoose');

// Connecting local mongodb database named test
var db = mongoose.connect('mongodb://127.0.0.1:27017/test');

// testing connectivity
mongoose.connection.once('connected', function() {
	console.log("Database connected successfully")
});

Now, let us use node to execute test_server.js. If you receive the message "database connected successfully", it means that the node.js application has successfully connected to the database.

$ node test_server.js
Database connected successfully

This article has ended here. For more other exciting content, you can pay attention to the Linux Video Tutorial column on the PHP Chinese website!

The above is the detailed content of How to connect Node.js program with MongoDB on CentOS and Fedora. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn