使用node.js对mongodb进行增删改查

tech2025-03-22  4

文章目录

准备工作导入一些准备好的数据 一、连接数据库二、增删改查1.创建集合添加数据2.查询文档3.删除文档4.更新文档


准备工作

使用Node.js操作MongoDB数据库需要依赖Node.js第三方包mongoose使用 npm install mongoose 命令下载

导入一些准备好的数据

下载好后,先提前往数据库中导入一些数据 这里有一个user.json文件,将其导入数据库中。

mongodb数据库导入数据 mongoimport -d 数据库名称 -c 集合名称 --file 要导入的数据文件 [{ "name": "张三", "age": 23, "email": "zhangsan@itcast.cn", "password": "123456" }, { "name": "李四", "age": 24, "email": "lisi@itcast.cn", "password": "123456" }, { "name": "王五", "age": 25, "email": "wangwu@itcast.cn", "password": "123456" }]

可以看到我这里的数据是以数组的形式存在的,所以导入数据的命令为:mongoimport -d 数据库名称 -c 集合名称 --jsonArray 要导入的数据文件 playground是数据库名称,mongodb中不需要显示创建数据库,如果正在使用的数据库不存在,MongoDB会自动创建。users是集合名称


一、连接数据库

使用mongoose提供的connect方法即可连接数据库。 mongodb中不需要显示创建数据库,如果正在使用的数据库不存在,MongoDB会自动创建。

const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/playground', { useUnifiedTopology: true, useNewUrlParser: true }) .then(() => console.log('数据库连接成功')) .catch((err) => console.log(err, '数据库连接失败'));

二、增删改查

1.创建集合添加数据

创建集合分为两步,一是对集合设定规则,二是创建集合,创建mongoose.Schema构造函数的实例即可创建集合

const userSchema = new mongoose.Schema({ name: String, age: Number, email: String, password: String }); const User = mongoose.model('User', userSchema);

创建文档实际上就是向集合中插入数据分为两步:创建集合实例调用实例对象下的save方法将数据保存到数据库中。

const User = mongoose.model('User', userSchema); const user = new User({ name: '赵六', age: 26, email: 'zhaoliu@qq.com', password: '123456' }); user.save();

也可以使用create()方法添加数据

User.create({ name: '赵六', age: 26, email: 'zhaoliu@qq.com', password: '123456' });

2.查询文档

//根据条件查询文档(条件为空则查找所有文档) User.find().then(result => console.log(result));

返回文档集合

[ { _id: 5f50e0d3a401ce13c3bd7329, name: '张三', age: 23, email: 'zhangsan@itcast.cn', password: '123456' }, { _id: 5f51909100637078988fe29f, name: '李四', age: 24, email: 'lisi@itcast.cn', password: '123456' }, { _id: 5f51909100637078988fe2a0, name: '王五', age: 25, email: 'wangwu@itcast.cn', password: '123456' }, { _id: 5f5198fe5a25a33ae0e8e93e, name: '赵六', age: 26, email: 'zhaoliu@qq.com', password: '123456', __v: 0 } ] //根据条件查找 User.find({ name: '张三' }).then(result => console.log(result));

返回结果:

//匹配大于 小于 User.find({age: {$lt: 20,$gt: 30}}).then(result => console.log(result)); //选择要查询的字段 User.find().select('name age').then(result => console.log(result)) //将数据按年龄进行排序 User.find().sort('age').then(result => console.log(result)) //skip 跳过多少数据 limit限制查询数量 User.find().skip(2).limit(2).then(result => console.log(result));

3.删除文档

//删除单个 User.findOneAndDelete({ name: '张三' }).then(result => console.log(result)) //删除多个 User.deleteMany({}).then(result => console.log(result))

4.更新文档

//更新单个 User.updateOne({ name: '张三'},{name: '张狗蛋' }).then(result => console.log(result)); //更新多个 User.updateMany({},{age:50}).then(result=>console.log(result)) //更新单个 User.updateOne({查询条件},{要更改的值}).then(result=>console.log(result)) //更新多个 User.updateMany({查询条件},{要更改的值}).then(result=>console.log(result)
最新回复(0)