JavaScript代码操作mongoDB数据库(使用Mongoose连接mongoDB数据库,进行增删改查操作)

在Node.js环境中,通过Mongoose库实现了连接MongoDB数据库的功能。详细介绍了如何创建db.js配置文件,定义student.js模型,以及在studentService.js中执行增、删、改、查操作。包括基本的文档插入,按ID更新和删除,条件查询,如分数范围、名字模糊匹配以及分页查询等实用场景。

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

创建文件夹(node.js环境下)
初始化包

npm init -y

下载mongoose

cnpm install mongoose

创建一个文件(db.js),并写入代码:

db.js文件:

// 引入
const mongoose=require('mongoose');

// 链接数据库
mongoose.connect('mongodb://localhost/cc');

// 数据库链接成功,执行下面的箭头函数
mongoose.connection.on('connected',()=> console.log('连接成功'));
// 数据库链接失败,执行下面的箭头函数,打印错误信息
mongoose.connection.on('error',(err)=> console.log(err));

// 上面链接数据库的代码只需要执行一次

右键----run code----链接成功:

E:\VSCode>node "e:\VSCode\Nodejs\24-Day10\02-mongooseDemo\db.js"
(node:7096) 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:7096) 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.
连接成功
  • Schema:Mongoose中的所有内容都以Schoma开头。每个Schema都映射到MongoDB集合,并定义该集合中的文档的结构
  • Model:由Schema生成的模型,其实例称为Document。一般用来负责从MongoDB查询文档,修改文档,删除文档
  • Document:Mongoose中Document与存储在MongoDB中的文档的一对一映射。每个文档都是其模型的一个实例。一般用来负责MongoDB保存文档
  • Schema类型:String、Number、Date…

student.js文件:

require('./db');

const mongoose=require('mongoose');
const Schema=mongoose.Schema;

// 定义集合里面的字段以及字段类型
let StudentSchema=new Schema({
   
    name: String,
    age: Number,
    score: Number
});

// 定义Model
// 参数1:对应的数据库中的集合名称,会自动加上s。如果没有这个数据库集合会自动创建。
// 参数2:Schema,用来封装查询的结果。
let Student=mongoose.model('student',StudentSchema);

// 暴露出去,给别的地方使用,避免重复定义
module.exports=Student;

studentService.js文件:

const Student = require('./students');

// 保存学生
function insert() {
   
    // 根据Model 创建 Document 对象
    let st
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值