IDEA2023.1.3破解,IDEA破解,IDEA 2023.1破解,最新IDEA激活码

二十六、Node.js 访问 MongoDB

IDEA2023.1.3破解,IDEA破解,IDEA 2023.1破解,最新IDEA激活码

文章永久连接:https://tech.souyunku.com/?p=5468

MongoDB 是一种文档导向的 NoSQL 数据库管理系统,由 C++ 撰写而成

本章节我们将学习如何使用 Node.js 来连接 MongoDB,并对数据库进行操作

如果你还没有 MongoDB 的基本知识,可以参考我们的 MongoDB 基础教程

安装 MongoDB 驱动

使用 NPM 安装 MongoDB 驱动 mongodb

$ npm install mongodb

安装完成后我们就可以使用 mongodb 模块访问 MongoDB 数据库了

引入 mongodb 模块

var driver = require('mongodb').MongoClient;

MongoDB 数据库操作( CURD )

与 MySQL 不同的是 MongoDB 会自动创建数据库和集合

因此使用前我们可以不需要手动去创建它们

插入数据

下面的范例我们访问数据库 souyunku 中的 site 表,并插入两条数据

main.js

/*
 * filename: main.js
 * author: 搜云库技术团队(tech.souyunku.com)
 * Copyright © 2015-2065 tech.souyunku.com. All rights reserved.
*/

var driver = require('mongodb').MongoClient;
var DB_CONN_STR = 'mongodb://localhost:27017/souyunku'; // 数据库为 souyunku

var insertData = function(db, callback) 
{  
    //连接到表 site
    var collection = db.collection('site');
    //插入数据
    var data = [{"name":"教程 ","url":"tech.souyunku.com"},{"name":"腾讯","url":"tech.souyunku.com"}];
    collection.insert(data, function(err, result) { 
        if(err)
        {
            console.log('Error:'+ err);
            return;
        }     
        callback(result);
    });
}

driver.connect(DB_CONN_STR, function(err, db) {
    console.log("连接成功!");
    insertData(db, function(result) {
        console.log(result);
        db.close();
    });
});

运行以上 Node.js 代码,输出结果如下

$ node main.js
连接成功!
{ result: { ok: 1, n: 2 },
  ops: 
   [ { name: '教程 ',
       url: 'tech.souyunku.com',
       _id: 59ef2c8af75bf73721c3e66b },
     { name: '腾讯', url: 'tech.souyunku.com', _id: 59ef2c8af75bf73721c3e66c } ],
  insertedCount: 2,
  insertedIds: [ 59ef2c8af75bf73721c3e66b, 59ef2c8af75bf73721c3e66c ] }

从输出结果来看,数据已插入成功

我们可以使用 mongo 命令行工具登录到 127.0.0.1:27017 的 MongoDB 服务器查看

$ mongo
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.9
> show dbs
admin       0.078GB
gridfs      0.078GB
test        0.078GB
souyunku        0.078GB
> use souyunku
switched to db souyunku
> show tables
counters
language
lession
site
system.indexes
users
> db.site.find()
{ "_id" : ObjectId("59ef2c8af75bf73721c3e66b"), "name" : "教程 ", "url" : "tech.souyunku.com" }
{ "_id" : ObjectId("59ef2c8af75bf73721c3e66c"), "name" : "腾讯", "url" : "tech.souyunku.com" }
> 

查询数据

使用 find() 方法从 site 集合中查找 name 为 “搜云库技术团队” 的数据

main.js

/*
 * filename: main.js
 * author: 搜云库技术团队(tech.souyunku.com)
 * Copyright © 2015-2065 tech.souyunku.com. All rights reserved.
*/

var driver = require('mongodb').MongoClient;
var DB_CONN_STR = 'mongodb://localhost:27017/souyunku'; // 数据库为 souyunku

var selectData = function(db, callback) {  
  //连接到表  
  var collection = db.collection('site');
  //查询数据
  var whereStr = {"name":'教程 '};
  collection.find(whereStr).toArray(function(err, result) {
    if(err)
    {
      console.log('Error:'+ err);
      return;
    }     
    callback(result);
  });
}

driver.connect(DB_CONN_STR, function(err, db) {
  console.log("连接成功!");
  selectData(db, function(result) {
    console.log(result);
    db.close();
  });
});

运行以上 Node.js 代码,输出结果如下

$ node main.js
连接成功!
[ { _id: 59ef2c8af75bf73721c3e66b,
    name: '教程 ',
    url: 'tech.souyunku.com' } ]

更新数据

update() 方法可以对数据库的数据进行修改

下面的范例我们将 name 为 “教程 ” 的 url 改为 https://tech.souyunku.com

main.js

/*
 * filename: main.js
 * author: 搜云库技术团队(tech.souyunku.com)
 * Copyright © 2015-2065 tech.souyunku.com. All rights reserved.
*/

var driver = require('mongodb').MongoClient;
var DB_CONN_STR = 'mongodb://localhost:27017/souyunku'; // 数据库为 souyunku

var updateData = function(db, callback) {  
    //连接到表  
    var collection = db.collection('site');
    //更新数据
    var whereStr = {"name":'教程 '};
    var updateStr = {$set: { "url" : "https://tech.souyunku.com" }};
    collection.update(whereStr,updateStr, function(err, result) {
        if(err)
        {
            console.log('Error:'+ err);
            return;
        }
        console.log("修改数据成功");
        callback(result);
    });
}

driver.connect(DB_CONN_STR, function(err, db) {
  console.log("连接成功!");
  updateData(db, function(result) {
    db.close();
  });
});

运行以上 Node.js 代码,输出结果如下

$ node main.js
连接成功!
修改数据成功

进入 mongo 管理工具查看数据已修改:

> db.site.find()
{ "_id" : ObjectId("59ef2c8af75bf73721c3e66b"), "name" : "教程 ", "url" : "https://tech.souyunku.com" }
{ "_id" : ObjectId("59ef2c8af75bf73721c3e66c"), "name" : "腾讯", "url" : "tech.souyunku.com" }
> 

删除数据

delete() 方法可以用来删除数据

下面的范例,我们将 name 为 “搜云库技术团队” 的数据删除

main.js

/*
 * filename: main.js
 * author: 搜云库技术团队(tech.souyunku.com)
 * Copyright © 2015-2065 tech.souyunku.com. All rights reserved.
*/

var driver = require('mongodb').MongoClient;
var DB_CONN_STR = 'mongodb://localhost:27017/souyunku'; // 数据库为 souyunku

var delData = function(db, callback) {  
  //连接到表  
  var collection = db.collection('site');
  //删除数据
  var whereStr = {"name":'教程 '};
  collection.remove(whereStr, function(err, result) {
    if(err)
    {
      console.log('Error:'+ err);
      return;
    }
    console.log("删除数据成功!")
    callback(result);
  });
}

driver.connect(DB_CONN_STR, function(err, db) {
  console.log("连接成功!");
  delData(db, function(result) {
    db.close();
  });
});

运行以上 Node.js 代码,输出结果如下

$ node main.js
连接成功!
删除数据成功!

进入 mongo 管理工具查看数据已删除:

> db.site.find()
{ "_id" : ObjectId("59ef2c8af75bf73721c3e66c"), "name" : "腾讯", "url" : "tech.souyunku.com" }

干货推荐

本站推荐:精选优质专栏

附录:Node.js 教程:系列文章


Warning: A non-numeric value encountered in /data/wangzhan/tech.souyunku.com.wp/wp-content/themes/dux/functions-theme.php on line 1154
赞(82) 打赏



未经允许不得转载:搜云库技术团队 » 二十六、Node.js 访问 MongoDB

IDEA2023.1.3破解,IDEA破解,IDEA 2023.1破解,最新IDEA激活码
IDEA2023.1.3破解,IDEA破解,IDEA 2023.1破解,最新IDEA激活码

评论 抢沙发

大前端WP主题 更专业 更方便

联系我们联系我们

觉得文章有用就打赏一下文章作者

微信扫一扫打赏

微信扫一扫打赏


Fatal error: Uncaught Exception: Cache directory not writable. Comet Cache needs this directory please: `/data/wangzhan/tech.souyunku.com.wp/wp-content/cache/comet-cache/cache/https/tech-souyunku-com/index.q`. Set permissions to `755` or higher; `777` might be needed in some cases. in /data/wangzhan/tech.souyunku.com.wp/wp-content/plugins/comet-cache/src/includes/traits/Ac/ObUtils.php:367 Stack trace: #0 [internal function]: WebSharks\CometCache\Classes\AdvancedCache->outputBufferCallbackHandler() #1 /data/wangzhan/tech.souyunku.com.wp/wp-includes/functions.php(5109): ob_end_flush() #2 /data/wangzhan/tech.souyunku.com.wp/wp-includes/class-wp-hook.php(303): wp_ob_end_flush_all() #3 /data/wangzhan/tech.souyunku.com.wp/wp-includes/class-wp-hook.php(327): WP_Hook->apply_filters() #4 /data/wangzhan/tech.souyunku.com.wp/wp-includes/plugin.php(470): WP_Hook->do_action() #5 /data/wangzhan/tech.souyunku.com.wp/wp-includes/load.php(1097): do_action() #6 [internal function]: shutdown_action_hook() #7 {main} thrown in /data/wangzhan/tech.souyunku.com.wp/wp-content/plugins/comet-cache/src/includes/traits/Ac/ObUtils.php on line 367