node.js operation mongodb learning summary

  • 2020-06-01 08:11:49
  • OfStack

1. Preparation

1. Create the table to read in mongodb

Create the database mongotest


use mongotest;

Insert data into the user table

db.user.insert({
name:'flyoung',
age:'18',
sex:true
});

2. Install node-mongodb-native

npm install mongodb

2. Instance (node.js reads mongodb)

Reference node mongodb - native document: https: / / github com mongodb/node mongodb -- native


var mongodb = require('mongodb'); var server = new mongodb.Server("127.0.0.1",27017,{});// local 27017 port new mongodb.Db('mongotest',server,{}).open(function(error,client){// Database: mongotest
    if(error) throw error;
    var collection = new mongodb.Collection(client,'user');// Table: user
    collection.find(function(error,cursor){
        cursor.each(function(error,doc){
            if(doc){
                console.log("name:"+doc.name+" age:"+doc.age);
            }
        });
    });
});

Run:

node mongodbTest.js

Results:

name:flyoung age:18

3. Write at the end

Add, delete, change and check demo reference document


Related articles: