君陌离的博客

vuePress-theme-reco 君陌离    2018 - 2020
君陌离的博客 君陌离的博客

Choose mode

  • dark
  • auto
  • light
首页
我的作品
  • 项目橱窗
  • blog模板
分类
  • 数据库
  • CSS
  • 摘记
  • JS
  • Node
  • Vue
  • React
  • GIT
  • Promise
  • Liunx
  • Xshell
  • ajax
  • WINDOWS
  • Python
  • 随笔
  • 脚手架
  • node
  • 自动化
标签
笔记
时间线
About Me
  • 关于我
  • 赞赏
Contact
  • GitHub
  • QQ
author-avatar

君陌离

70

文章

90

标签

首页
我的作品
  • 项目橱窗
  • blog模板
分类
  • 数据库
  • CSS
  • 摘记
  • JS
  • Node
  • Vue
  • React
  • GIT
  • Promise
  • Liunx
  • Xshell
  • ajax
  • WINDOWS
  • Python
  • 随笔
  • 脚手架
  • node
  • 自动化
标签
笔记
时间线
About Me
  • 关于我
  • 赞赏
Contact
  • GitHub
  • QQ
  • HTML5

  • JS

  • 微信小程序

  • 数据库

    • Node.js 连接 MongoDB
    • Node.js 连接 MySQL
  • React

  • Vue

  • vuepress

Node.js 连接 MongoDB

vuePress-theme-reco 君陌离    2018 - 2020

Node.js 连接 MongoDB

君陌离 2018-08-07 MongoDB

# 密码登录

mongoose.connect('mongodb://username:password@host:port/database?options...');
1

# 无密码

mongoose.connect('mongodb://host:port/database?options...');
1

# 安装依赖

cnpm install mongodb
1

# 连接 MongoDB

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://username:password@119.45.212.92:27017/";

MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("blog");
    dbo.collection("members"). find({}).toArray(function(err, result) { // 返回集合中所有数据
        if (err) throw err;
        console.log(result);
        db.close();
    });
});
1
2
3
4
5
6
7
8
9
10
11
12

# Promise 数据操作

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://username:password@119.45.212.92:27017/";
MongoClient.connect(url, { useNewUrlParser: true }).then((conn) => {
    console.log("数据库已连接");
    const test = conn.db("testdb").collection("test");
    // 增加
    test.insertOne({ "site": "runoob.com" }).then((res) => {
        // 查询
        return test.find().toArray().then((arr) => {
            console.log(arr);
        });
    }).then(() => {
        // 更改
        return test.updateMany({ "site": "runoob.com" },
            { $set: { "site": "example.com" } });
    }).then((res) => {
        // 查询
        return test.find().toArray().then((arr) => {
            console.log(arr);
        });
    }).then(() => {
        // 删除
        return test.deleteMany({ "site": "example.com" });
    }).then((res) => {
        // 查询
        return test.find().toArray().then((arr) => {
            console.log(arr);
        });
    }).catch((err) => {
        console.log("数据操作失败" + err.message);
    }).finally(() => {
        conn.close();
    });
}).catch((err) => {
    console.log("数据库连接失败");
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

# 更多精彩内容

Node.js 连接 MongoDB
mongo操作
liunx开启远程连接数据库

欢迎来到 您的站点名称($site.title)
看板娘