创建文件夹(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

在Node.js环境中,通过Mongoose库实现了连接MongoDB数据库的功能。详细介绍了如何创建db.js配置文件,定义student.js模型,以及在studentService.js中执行增、删、改、查操作。包括基本的文档插入,按ID更新和删除,条件查询,如分数范围、名字模糊匹配以及分页查询等实用场景。
最低0.47元/天 解锁文章
&spm=1001.2101.3001.5002&articleId=108513273&d=1&t=3&u=f7757dbcd0ff4a10a4902bf6c0ef6d0f)
1万+

被折叠的 条评论
为什么被折叠?



