登录  /  注册
首页 > web前端 > js教程 > 正文

使用Nodejs连接mongodb数据库的实现

不言
发布: 2018-06-30 11:48:28
原创
1118人浏览过

这篇文章主要介绍了使用nodejs连接mongodb数据库的实现代码,需要的朋友可以参考下

一个简单的nodejs连接mongodb示例,来自 mongodb官方示例

1. 创建package.json

首先,创建我们的工程目录connect-mongodb,并作为我们的当前目录

mkdir connect-mongodb
cd connect-mongodb
登录后复制

输入npm init命令创建package.json

npm init
登录后复制

然后,安装mongodb的nodejs版本driver

npm install mongodb --save
登录后复制

mongodb驱动包将会安装到当前目录下的node_modules中

2. 启动MongoDB服务器

安装MongoDB并启动MongoDB数据库服务,可参考我之前的文章,或者MongoDB官方文档

3. 连接MongoDB

创建一个app.js文件,并添加以下代码来连接服务器地址为192.168.0.243,mongodb端口为27017上名称为myNewDatabase的数据库

var MongoClient = require('mongodb').MongoClient,
  assert = require('assert');
// Connection URL
var url = 'mongodb://192.168.0.243:27017/myNewDatabase';
MongoClient.connect(url,function(err,db){
  assert.equal(null,err);
  console.log("Connection successfully to server");
  db.close();
});
登录后复制

在命令行输入以下命令运行app.js

node app.js
登录后复制

4. 插入文档

在app.js中添加以下代码,使用insertMany方法添加3个文档到documents集合中

var insertDocuments = function(db, callback){
  // get ths documents collection
  var 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);
  });
};
登录后复制

insert命令返回一个包含以下属性的对象:

  • result MongoDB返回的文档结果

  • ops 添加了_id字段的文档

  • connection 执行插入操作所使用的connection

在app.js更新以下代码调用insertDocuments方法

var MongoClient = require('mongodb').MongoClient
 , assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
 assert.equal(null, err);
 console.log("Connected successfully to server");
 insertDocuments(db, function() {
  db.close();
 });
});
登录后复制

在命令行中使用node app.js运行

5. 查询所有文档

添加findDocuments函数

var findDocuments = function(db,callback){
  // get the documents collection
  var 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);
  });
};
登录后复制

findDocuments函数查询了所有'documents'集合中所有的文档,将此函数添加到MongoClient.connect的回调函数中

var MongoClient = require('mongodb').MongoClient
 , assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
 assert.equal(null, err);
 console.log("Connected correctly to server");
 insertDocuments(db, function() {
  findDocuments(db, function() {
   db.close();
  });
 });
});
登录后复制

6. 使用过滤条件(query filter)查询文档

查询'a':3的文档

var findDocuments = function(db, callback) {
 // Get the documents collection
 var collection = db.collection('documents');
 // Find some documents
 collection.find({'a': 3}).toArray(function(err, docs) {
  assert.equal(err, null);
  console.log("Found the following records");
  console.log(docs);
  callback(docs);
 });   
}
登录后复制

7. 更新文档

var updateDocument = function(db,callback){
  // get the documents collection
  var collection = db.collection('documents');
  // update document where a is 2, set b equal to 1
  collection.updateOne({a:2},{
    $set:{b:1}
  },function(err,result){
    assert.equal(err,null);
    assert.equal(1,result.result.n);
    console.log("updated the document with the field a equal to 2");
    callback(result);
  });
};
登录后复制

updateDocument方法更新满足条件a为2的第一个文档,新增一个b属性,并将其设置为1。

将updateDocument方法添加到MongoClient.connect方法的回调中

MongoClient.connect(url,function(err,db){
  assert.equal(null,err);
  console.log("Connection successfully to server");
  insertDocuments(db,function(){
    updateDocument(db,function(){
      db.close();
    });
  });
});
登录后复制

8. 删除文档

var removeDocument = function(db,callback){
  // get the documents collection
  var collection = db.collection('documents');
  // remove some documents
  collection.deleteOne({a:3},function(err,result){
    assert.equal(err,null);
    assert.equal(1,result.result.n);
    console.log("removed the document with the field a equal to 3");
    callback(result);
  });
};
登录后复制

添加到app.js中

var MongoClient = require('mongodb').MongoClient
 , assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
 assert.equal(null, err);
 console.log("Connected successfully to server");
 insertDocuments(db, function() {
  updateDocument(db, function() {
   removeDocument(db, function() {
    db.close();
   });
  });
 });
});
登录后复制

9. 创建索引

索引能够改善应用的性能。下面你代码在'a'属性上添加索引

var indexCollection = function(db,callback){
  db.collection('documents').createIndex({
    a:1
  },null,function(err,results){
    console.log(results);
    callback();
  });
};
登录后复制

更新app.js

MongoClient.connect(url,function(err,db){
  assert.equal(null,err);
  console.log("Connection successfully to server");
  insertDocuments(db,function(){
    indexCollection(db,function(){
      db.close();
    });
  });
});
登录后复制

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

node-mysql中防止SQL注入的方法

NodeJs form-data格式传输文件的方法

以上就是使用Nodejs连接mongodb数据库的实现的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
关于CSS思维导图的课件在哪? 课件
凡人来自于2024-04-16 10:10:18
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号