好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

使用Node操作MongoDB数据库的方法

1.使用 MongoDB模块 进行操作

 首先在工作目录安装 mongodb 模块,

?

1

cnpm i mongodb //引入模块

?

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

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

//写连接字符串,我的数据库地址如下,所以当你在写的时候修改地址之后的内容就好

const DB_CONN_STR= 'mongodb://127.0.0.1/demo' ;

//记得打开mongod服务 ,不然等着一堆err吧

//写一个插入数据的函数

const insertData = function (db,callback){

   let collection = db.collection( '集合名' );

   let data = [{ "name" : "AAA" , "age" : "19" },{ "name" : "BBB" , "age" : "20" }]

    // 向集合中添加数据

   collection.insert(data, function (err,result){

     if (err){

       console.log( 'Error' +err);

       return ;

     }

     callback(result);

   }); 

}

//连接数据库      连接串    回调函数

MongoClient.connect(DB_CONN_STR, function (err, db) {

   console.log( "Done" );

   //调用刚才写好的函数

    insertData(db, function (result) {

      //输出返回结果

     console.log(result);

      //关闭连接

      db.close();

    });

});

2.使用 Mongoose模块 进行操作

 2.1 创建文件db.js用来连接(其实这一步也有一点问题,不应该把数据库连接写到这里)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

//创建文件 db.js

// 在这之前你应该已经安装了 mongoose || cnpm install mongoose

// 并且开启了mongod服务

import mongoose from 'mongoose' ;

//mongoose.connect('mongodb://127.0.0.1:27017/demo');

//如果只是入地址,会报一个警告,不是错误,只属于是不推荐的写法.推荐下面这么写

mongoose.connect( 'mongodb://地址/数据库名' ,{useMongoClient: true });

const db = mongoose.connection;

//

db.on( 'error' ,console.error.bind(console, 'connection error:' ));

db.once( 'open' , function (callback){

    console.log( "connection start" );

});

db.on( 'disconnected' , function (){

   console.log( "connstion is disconnected" );

});

module.exports = mongoose;

 2.2 Shema

创建文件stu.js保存操作

Mongoose中的一切来自于Schema。每个Schema都会映射到MongoDB集合(collection)并定义该集合(collection)中的文档的 形状(类型)。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

// 如名字所示,我们要创建的是 名字为 user 的Schmea

//如果以后要添加其他键,请使用Schema.add({})方法。

//引入刚才写好的模块

import mongoose from './db'

const Shema = mongoose.Schema;

const UserShema = new Schema({

   name : {type:String},

   age : {type:Number},

   class : {type:String}

})

// Schema Types内置类型如下:

// String,Number,Boolean | Bool,Array,Buffer,Date,ObjectId | Oid,Mixed

// 如果你发现少了什么属性,可以使用 Shame.add();追加

UserShema.add{mail : 'String' ,pwd : 'String' }

// 然后使用 Schema 创建我们的model ,再加入到模块,这一步骤很重要

module.exports = mongoose.model( 'Student' ,UserSchema)

   2.3 Shema 的使用(增加篇)

?

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

//

//在 import user.js的时候 启动了 mongoose.model('Classes',ClassSchema);参见上面的最后一段代码

import student from './stu'

class mannager{

   //第一种创建方式

   add(){

     let newStu = new student({

     name : '张三' ,

     age : 25,

     class : '大四'

     });

     newStu.save( function (err) {

     if (err)

       return handleError(err);

     });

   }

   //第二种创建方式

   add2(){

     student.create({

      name : '张三' ,

      age : 25,

      class : '大四'

     }, function (err){

       if (err)

         return handleError(err);

     });

   }

   }

  Shema 的使用(查询篇)

 mongoose

支持丰富的查询MongoDB语法。文件可以使用每个模型中使用 find,findById,findOne,或者where,静态方法。  

?

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

//查询所有

   findAll(){

    return student.find( function (err,res){

       if (err) {

         return err;

       } else {

         let json = JSON.stringify(res);

         return res;

       }

     });

   }

   //按照条件查询

   findByAge(age){

     return student.find({Age : age}, function (err,res){

       if (err) {

         return err;

       } else {

         let json = JSON.stringify(res);

         return res;

       }

     });

   }

   //多种条件

   findTest(){

     return Tank.find(

       { class: '大三' }).where( 'Age' ).gt(20).exec(callback);

   }

API文档包含了许多额外的方法,像 count,mapReduce,aggregate,更多。在这里就不一一举栗子了

总结

以上所述是小编给大家介绍的使用Node操作MongoDB数据库的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:https://HdhCmsTestcnblogs测试数据/Molyp/archive/2018/01/11/8260753.html

查看更多关于使用Node操作MongoDB数据库的方法的详细内容...

  阅读:19次