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

Why node.js always uses mongo

(*-*)浩
(*-*)浩Original
2019-05-20 14:46:372893browse

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);

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();
        })
    })
})

(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');

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!

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