Home > Web Front-end > JS Tutorial > Why node.js always uses mongo

Why node.js always uses mongo

(*-*)浩
Release: 2020-09-19 11:53:08
Original
2954 people have browsed it

Why node.js always uses mongo

node.js provides a variety of drivers for operating mongodb, including mongoose, mongoskin, node-mongodb-native (official), etc.

The author's explanation on the mongoose official website:

The Mongoose library is simply a convenient encapsulation and an object model for operating the MongoDB database in the node environment. Tools, similar to ORM, Mongoose converts data in the database into JavaScript objects for use in your application

Example:

1. Introduce dependency packages :

npm install mongodb --save-dev

2. Create a simple service and introduce dependency packages:

var express = require('express');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var dbURL = 'mongodb://localhost:27017';
app.listen(process.env.POST || 8080);
Copy after login

3. Write a route

 app.get('/insert',function(req, res) {
    MongoClient.connect(dbURL,function(err, db) {

        assert.equal(err,null);
        const person = db.db('person');
        const student = person.collection('student');

        student.insertOne({

            "name": "insert in nodejs"

        },function(error, result) {
            var re = JSON.parse(result);
            if (re.n === 1) {
                res.send("插入成功。");
            } else {
                res.send("插入失败,error:" + error);
            }
            res.end();
            db.close();
        })
    })
})
Copy after login

(1) Connect to the database: connect(dbURL,callback)
(2) Get the database to be operated, and then get the table to be operated:

 var dbURL = 'mongodb://localhost:27017/person';
 var student = db.collection('student');
Copy after login

Access in the browser, and then use the command to check whether the insertion is successful:

Why node.js always uses mongo

Related learning recommendations: js video tutorial

The above is the detailed content of Why node.js always uses mongo. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template