当前位置: 首页 > 后端技术 > Node.js

Node.js学习之路23——Node.js使用mongoose连接mongodb数据库

时间:2023-04-03 20:49:35 Node.js

Node.js使用mongoose连接mongodb数据库Node.js连接mongodb数据库的方式有很多种,其中一种其中引入了mongoose模块结构|---|根目录|---|---|connect.js(mongoose测试连接)|---|---|user.js(定义用户数据表)|---|---|operate.js(定义mongodb的增删改查功能)|---|---|login.js(Node后台调用operate.js文件的方法处理数据)1.介绍mongoose测试连接目前使用的mongoose版本For4.13.7文件为connect.js1.1代码部分constmongoose=require("mongoose");constDB_URL="mongodb://127.0.0.1:27017/infos";mongoose.Promise=global.Promise;mongoose.connect(DB_URL,{useMongoClient:true});mongoose.connection.on("connected",()=>{console.log("mongodb数据库连接成功")});mongoose.connection.on("error",(error)=>{console.log("mongodbdatabaseconnectionfailed",error)});module.exports=mongoose;1.2代码分析1.2.1引入猫鼬模块constmongoose=require("mongoose");1.2。2获取mongodb本地地址constDB_URL="mongodb://127.0.0.1:27017/infos";127.0.0.1是本地IP地址27017是mongodb的服务启动端口infos是mongodb的数据集合名称mongodb可以有很多数据集合,每个集合可以有很多数据表。打个比方:你有一个巨型停车场(mongodb),里面分为不同的停车区(collection,infoshere),每个停车区可以停很多车((下面提到的user),相当于每个数据都有可以集合中的许多数据表)。如果需要给mongodb添加用户和密码,可以constDB_URL="mongodb://username:password@127.0.0.1:27017/infos";其中username为用户名,中间英文:,password为密码,其余不变1.2.3连接数据库成功mongoose.connection.on("connected",callback())连接数据库后成功后,控制台会输出mongodb数据库连接成功1.2.4连接数据库失败mongoose.connection.on("error",callback())连接数据库成功后,mongodb数据库连接失败和控制台会输出错误信息1.2.5导出mongoose模块module.exports=mongoose;2.定义每个数据表的字段。文件为user.js2.1代码介绍constmongoose=require('mongoose');constdb=require('./connect.js');constuserSchema=newmongoose.Schema({number:{type:Number},email:{type:String},password:{type:String},rePassword:{type:String},mobile:{type:String},问题:{type:String},answer:{type:String},});letuserModel=db.model('user',userSchema);module.exports=userModel;2.2代码分析2.2.1引入mongoose模块constmongoose=require("mongoose");2.2.1引入连接mongodb数据库的模块constdb=require('./connect.js');2.2.2定义SchemaconstuserSchema=newmongoose.Schema({})passmongoose对象的Schema属性创建一个Schema对象。Schema的本意是模式。在mongodb中,每个数据字段都必须有固定的数据类型,所以mongoose中Schema的含义就是每个数据表对应的字段的数据类型。Schema可以拥有的数据类型如下:StringNumberDateBufferBooleanMixedObjectIdArray字段介绍,以number字段为例,type是这个字段的数据类型,default是这个字段的默认值,还有很多其他的属性,以及可自定义的属性2.2.3确认数据表和数据表的字段letuserModel=db.model('user',userSchema);使用db.model方法定义一个数据表userModel,第一个参数是数据表的名称,第二个参数是数据表使用的Schema2.2.4最后导出定义的数据表module.exports=userModel;导出后在operate.js中使用该对象进行增删改查方法3.定义mongodb增删改查函数3.1代码部分文件为operate.jsletuserModel=require('./用户.js');module.exports={save(data){returnnewPromise((resolve,reject)=>{userModel.create(data,(err,docs)=>{if(err){rejct(err);}else{resolve(docs);}})})},find(data={},fields=null,options={}){returnnewPromise((resolve,reject)=>{//model.find(要找到的对象(如果为空,则查找所有数据),attributefilterobject[可选参数],options[可选参数],callback)userModel.find(data,fields,options,(error,doc)=>{if(error){reject(error)}else{resolve(doc)}})})},findOne(data){returnnewPromise((resolve,reject)=>{//model.findOne(要找到的对象,回调)userModel.findOne(data,(error,doc)=>{if(error){reject(error)}else{resolve(doc)}})})},findById(data){返回新的Promise((resolve,reject)=>{//model.findById(id待搜索对象,回调)userModel.findById(data,(error,doc)=>{if(error){reject(error)}else{resolve(doc)}})})},update(conditions,update){returnnewPromise((resolve,reject)=>{//model.update(querycondition,updateobject,callback)userModel.update(conditions,update,(error,doc)=>{if(error){reject(error)}else{resolve(doc)}})})},remove(conditions){returnnewPromise((resolve,reject)=>{//model.update(查询条件,callback)userModel.remove(conditions,(error,doc)=>{if(error){reject(error)}else{resolve(doc)}})})}};3.2代码分析引入用户模块letuserModel=require('../models/users');引入这个文件的目的是让userModel数据表直接调用mongodb4的各种方法,后台直接使用operate处理数据。这个文件是login.js4.1的代码部分constexpress=require('express');constrouter=express.Router();letoperate=require('./operate');router.post('/',function(req,res,next){letparam={};param.email=req.body.email;param.password=req.body.password;console.log(param);operate.save(param).then(result=>{if(result){res.json({data:result,success:true})}else{res.json({data:result,success:false})}});});module.exports=路由器;4.2代码分析需要熟练使用Express的router方法导入Express,定义一个post方法。post方法传递的对象数据挂在req.body上直接调用operate.save()方法,传递param对象参数得到返回的result结果,对得到的结果做进一步处理