MongoDB快速入门教程 (4.1)

4.Mongoose使用

4.1.nodejs操作mongodb

文档地址:http://mongodb.github.io/node-mongodb-native/3.2/tutorials/crud/

1.安装mongodb驱动

npm install mongodb --save-dev

2.连接数据库

const MongoClient = require('mongodb').MongoClient;
var dburl = "mongodb://admin::27017";
MongoClient.connect(dburl, {useNewUrlParser:true}, (err,client)=>{
    if(err){
        console.log('数据库连接失败!');
        return;
    };
    const db = client.db("test")
    
});

3.插入数据

const MongoClient = require('mongodb').MongoClient;
var url = "mongodb://admin::27017";
var client = new MongoClient(url)
client.connect((err,client)=>{
    if(err){
        console.log('数据库连接失败!');
        return;
    };
    const db = client.db("test")
    // 插入数据
    db.collection("user").insertOne({"name": "nodeing", "age": 18}, (err, result) => {
      console.log(result)
    })
});

4.更新数据

const MongoClient = require('mongodb').MongoClient;
var url = "mongodb://admin::27017";
var client = new MongoClient(url)

client.connect((err,client)=>{
    if(err){
        console.log('数据库连接失败!');
        return;
    };
    const db = client.db("test")
    db.collection('user').updateOne({"name": "nodeing"}, {$set: {"age": 38}}, (err, result)=>{
        console.log(result)
        client.close();
    })
});

5.删除数据

const MongoClient = require('mongodb').MongoClient;
var url = "mongodb://admin::27017";
var client = new MongoClient(url)

client.connect((err,client)=>{
    if(err){
        console.log('数据库连接失败!');
        return;
    };
    const db = client.db("test")
    db.collection('user').deleteOne({"name": "nodeing"}, (err, result)=>{
        console.log(result)
        client.close();
    })
});

螺钉课堂视频课程地址:http://edu.nodeing.com

相关推荐