使用mongoose在nodeJs里操作mongoDB数据库

本文详细介绍如何在Node.js环境中启动并连接MongoDB数据库,包括安装mongoose模块、配置连接选项、执行基本CRUD操作等核心步骤。

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

启动mongoDB

1、终端中输入mongod,启动mongo服务端,出现下面的样子就是启动成功了。

使用mongoose在nodeJs里操作mongoDB数据库
2、新建一个终端窗口,输入mongo,出现下面的样子就是启动成功了。

使用mongoose在nodeJs里操作mongoDB数据库
3、mongo启动成功后,就可以对数据库进行操作了。

使用mongoose在nodeJs里操作mongoDB数据库
点击https://blog.youkuaiyun.com/Charissa2017/article/details/105016264查看mongdb简介及常用的命令

Node连接mongoDB

node连接mongodb,需要使用第三方模块mongoose,mongoose支持promises或者回调。

1、安装

npm install mongoose
或者使用yarn安装
yarn add mongoose

2、使用require引入到模块中

const mongoose=require("mongoose");

3、连接到mongodb

mongodb 终端中输入db.getMongo(),获取连接地址

mongodb
nodeJs中,使用connect()方法进行连接。

  • 第一个参数为数据库地址,协议是mongodb:,host为mongodb的连接地址,后面跟要连接的数据库名称。
  • 使用新版本的mongoose,需要在第二个参数option中设置useNewUrlParser和useUnifiedTopology为true。否则将会出现以下警示:

(node:86213) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
(node:86213) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.

nodeJs中写入以下代码:

mongoose.connect("mongodb://127.0.0.1:27017/test",{
    useNewUrlParser: true,
    useUnifiedTopology: true
});

连接后,将open在Connection实例上触发事件,Connection为mongoose.connection。

var db=mongoose.connection;

//连接失败时执行
db.on("error",console.error.bind(console,"connect fail"));
//连接成功后执行
db.on("open",()=>{
    console.log("we are connected~")
})

到这里,我们就可以实现node连接mongodb了。

4、通过node操作mongodb

通过mongoose.model()定义一个模型,mongoose.model()中,
第一个参数为数据库中集合的名称,
第二个参数为该集合中字段的名称和类型

对数据的操作需要使用promise或者回调函数,如果使用回调函数的话,按照Node错误优先的原则 ,第一个为err,第二个参数为执行操作后返回的内容,跟使用命令行操作mongodb是一样的。

继续上面的文件内容:

//定义一个模型
var UserModel = mongoose.model("users",{
    name:String,
    age:Number,
    sex:String,
    address:String
})

//查看当前集合中的所有内容
async function find(){
    let rs=await UserModel.find({});
    console.log(rs);
}
find();

//添加数据 
function add() {
	UserModel.insertMany([{ name: 'user5', age: 20 }, { name: 'user6', age: 21 }], function (err, docs) {
		console.log(docs);
		//[ { _id: 5e7892cc982ba0516ddb16e7, name: 'user5', age: 20, __v: 0 },
		//{ _id: 5e7892cc982ba0516ddb16e8, name: 'user6', age: 21, __v: 0 } ]
	})
}
add();

//修改数据
async function update(){
   let rs=await UserModel.update({name:"zhangsan"},{$set:{age:33}});
   console.log(rs); //{ n: 1, nModified: 1, ok: 1 }
}
update();
 
//删除数据
function del(){
    UserModel.deleteMany({name: 'user5'},function(err,docs){
        console.log(docs); //{ n: 1, ok: 1, deletedCount: 1 }
    })
}
del(); 

对数据的操作命令可以查看mongoose官网API文档:http://www.mongoosejs.net/docs/api.html#Model

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值