mongodb与node

本文介绍了如何使用Node.js连接MongoDB并进行基础的数据库操作,包括连接数据库、创建文档、查询数据、更新和删除文档,以及使用async/await处理异步操作,提供了一个简单的MongoDB操作示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文主要讲node是如何连接mongodb,并做基本的增删改查操作
mongodb的安装不多赘述,可参考菜鸟教程
mongodb与mysl的性能分析
本文参考地址: https://github.com/mongodb/node-mongodb-native
官方API文档:https://mongodb.github.io/node-mongodb-native/3.0/api/

本文项目环境: ubuntu16.04 node@v8.10.0 npm@6.1.0

  • 创建项目路径
 mkdir test_mongodb
  • 初始化项目结构,并安装mongodb的依赖包
npm init
npm install mongodb --save
  • 创建数据库目录并开启mongodb
mongod --dbpath=/data
  • 创建app.js文件,并连接数据库myproject
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
    
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);

  client.close();
});

执行命令可检测是否连接成功

node app.js
  • 将多个数据插入文档
const insertDocuments = function(db, callback) {
    
  // Get the documents collection
  const collection = db.collection('documents');
  // Insert some documents
  collection.insertMany([
    {
    a : 1}, {
    a : 2}, {
    a : 3}
  ], function(err, result) {
    
    assert.equal(err, null);
    assert.equal(3, result.result.n);
    assert.equal(3, result.ops.length);
    console.log("Inserted 3 documents into the collection");
    callback(result);
  });
}

其中,文档对应mysql中的表,在上段代码中文档名为documents,
将上述方法添加进app.js

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
    
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);

  insertDocuments(db, function() {
    
    client.close();
  });
});

运行程序可查看返回结果

node app.js
  • 查询所有文档
const findDocuments = function(db, callback) {
    
  // Get the documents collection
  const collection = db.collection('documents');
  // Find some documents
  collection.find({
    }).toArray(function(err, docs) {
    
    assert.equal(err, null);
    console.log("Found the following records");
    console.log(docs)
    callback(docs);
  });
}

find()方法中可添加查询条件,上述代码中为空,所以为查询所有文档,在app.js中添加该方法

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
    
  assert
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值