100 # mongoose 的使用

news/2025/3/14 5:49:58/

mongoose

elegant mongodb object modeling for node.js

https://mongoosejs.com/

安装 mongoose

npm i mongoose

基本示例

const mongoose = require("mongoose");// 1、连接 mongodb
let conn = mongoose.createConnection("mongodb://kaimo313:kaimo313@localhost:27017/user", {useNewUrlParser: true,useUnifiedTopology: true
});
conn.on("connected", () => {console.log("链接成功");
});// 2、Schema 骨架,根据这个骨架来创建内容,用来规范文档的
let StudentSchema = new mongoose.Schema({username: {type: String,required: true},password: String,age: Number,birthday: {type: Date,default: Date.now}},{collection: "Student" // 设置固定的名字}
);// 3、通过骨架来创建模型 -> 集合 db.student.insert()
let Student = conn.model("Student", StudentSchema);// 4、模型可以操作数据
Student.create({username: "kaimo001",password: "kaimo001",test: "测试多余数据"
}).then((doc) => {console.log(doc);
});

启动

nodemon mongoose.js

在这里插入图片描述

在这里插入图片描述

新增改查,分页

const mongoose = require("mongoose");// 1、连接 mongodb
let conn = mongoose.createConnection("mongodb://kaimo313:kaimo313@localhost:27017/user", {useNewUrlParser: true,useUnifiedTopology: true
});
conn.on("connected", () => {console.log("链接成功");
});// 2、Schema 骨架,根据这个骨架来创建内容,用来规范文档的
let StudentSchema = new mongoose.Schema({username: {type: String,required: true},password: String,age: Number,birthday: {type: Date,default: Date.now},hobby: [String]},{collection: "Student" // 设置固定的名字}
);// 3、通过骨架来创建模型 -> 集合 db.student.insert()
let Student = conn.model("Student", StudentSchema);// 4、模型可以操作数据
(async () => {// 1) 批量插入:let arr = [];for (let i = 0; i < 4; i++) {arr.push({username: "kaimo" + i,password: "kaimo" + i,age: i});}let r1 = await Student.create(arr);console.log("批量插入----->", r1);// 2) 查询操作:findOne 是查询一个;find 是查询一组,查询的结果只采用某个几个字段// _id 比较特殊需要单独控制,username: 1, password: 1 表示显示该字段let r2 = await Student.findOne({ username: "kaimo1" }, { username: 1, password: 1 });// await Student.findById("652e81753e38c888970b3846");console.log("查询操作----->", r2);// 3) 修改操作 (查询条件,修改成的结果)// 修改所有年龄大于2的,年龄都加10// where 基本不用,性能差 ({$where: "age>2"})// 操作符:lt: 小于 gt:大于 lte:小于等于 lgt:大于等于 inc:递增let r3 = await Student.updateOne({ age: { $gt: 2 } }, { $inc: { age: 10 } });console.log("修改操作--r3--->", r3);// 加个字段,新增 setlet r4 = await Student.updateOne({ username: /kaimo1/ }, { $set: { password: "123456" } });console.log("修改操作--r4--->", r4);// 数组新增用 push,不重复添加用 addToSetlet r5 = await Student.updateOne({ username: /kaimo1/ }, { $push: { hobby: ["睡觉1", "睡觉2"] } });console.log("修改操作--r5--->", r5);// 多条件(or)删除(pop)数组第一个let r6 = await Student.updateOne({ $or: [{ username: /kaimo1/ }, { age: 1 }] }, { $pop: { hobby: -1 } });console.log("修改操作--r6--->", r6);// 4) 删除// Student.deleteOne(); Student.deleteMany();// 5) 分页查询let limit = 2; // 每页2条let currentPage = 2; // 当前是第2页let skip = (currentPage - 1) * limit;// find 返回的是一个游标,并不是一个结果;查询 -> 排序 -> 跳过 -> 限制let r7 = await Student.find({}).limit(limit).skip(skip).sort({ age: -1 });console.log("分页查询--r7--->", r7);
})();

连表查询

const mongoose = require("mongoose");// 1、连接 mongodb
let conn = mongoose.createConnection("mongodb://kaimo313:kaimo313@localhost:27017/user", {useNewUrlParser: true,useUnifiedTopology: true
});
conn.on("connected", () => {console.log("链接成功");
});// 学生模型
let StudentSchema = new mongoose.Schema({username: {type: String,required: true},password: String,age: Number,birthday: {type: Date,default: Date.now},hobby: [String]},{collection: "Student" // 设置固定的名字}
);let Student = conn.model("Student", StudentSchema);// 作业模型
let HomeWorkSchema = new mongoose.Schema({title: String,content: String,student: {ref: "Student",type: mongoose.SchemaTypes.ObjectId // 用户id}},{collection: "Homework" // 设置固定的名字}
);
let HomeWork = conn.model("Homework", HomeWorkSchema);(async () => {let user = await Student.create({ username: "kaimo666", password: "123456" });let home = await HomeWork.create({title: "第一篇作业",content: "第一篇作业的内容",student: user._id});console.log(home);// 连表查询let r = await HomeWork.findById("653538ed066785338ab72d81").populate("student", { username: 1 });console.log("连表查询--r-->", r);// 修改:通过模型来操作;通过文档自己操作自己r.title = "修改后的标题";await r.save();
})();

http://www.ppmy.cn/news/1171368.html

相关文章

【milkv】internal codec -- mic

文章目录 一、硬件二、dts三、配置引脚board_initpin 四、makefile五、config六、添加tinyalsa七、测试结果7.1 查看录制device信息7.2 录制音频7.3 pc端获取录制好的设备7.4 使用audacity查看波形 一、硬件 i2s0 —— adc i2s1 —— pdm i2s3 —— dace spk_en存疑 i2s2 ——…

海外ASO优化之如何优化应用页面上的视频

据统计&#xff0c;观看视频的用户&#xff0c;安装应用的可能性增加了3倍。视频因其动态性而更能吸引注意力&#xff0c;并传达更多有关游戏的信息&#xff0c;强调要点和独特功能&#xff0c;这反过来又会影响转化。 1、技巧。 最重要的部分是视频的前几秒钟。因为这决定了用…

029-第三代软件开发-加载本地字体库

第三代软件开发-加载本地字体库 文章目录 第三代软件开发-加载本地字体库项目介绍加载本地字体库 关键字&#xff1a; Qt、 Qml、 QFont、 QFontDatabase、 ttf 项目介绍 欢迎来到我们的 QML & C 项目&#xff01;这个项目结合了 QML&#xff08;Qt Meta-Object Langu…

IP代理是什么?有什么好处?

IP说简单不简单&#xff0c;说复杂也不复杂&#xff0c;打个比方&#xff0c;IP就好比我们上网的一个门牌号&#xff0c;每家每户都会有一个门牌号&#xff0c;而且是唯一的地址。而代理IP&#xff08;代理服务器&#xff09;是一个位于中间的服务器&#xff0c;充当客户端和目…

设置Unity URP管线中的渲染开关

在上一节中&#xff0c;我们添加了外轮廓线&#xff0c;但这个外轮廓线在所有使用该Shader的网格上是始终存在的。 如果我们想做一个开关&#xff0c;决定是否打开外轮廓线时&#xff0c;我们可以使用一个新的Uniform bool值&#xff0c;然后判断bool是否为true来开启外轮廓线…

城市正视图(Urban Elevations, ACM/ICPC World Finals 1992, UVa221)rust解法

如图5-4所示&#xff0c;有n&#xff08;n≤100&#xff09;个建筑物。左侧是俯视图&#xff08;左上角为建筑物编号&#xff0c;右下角为高度&#xff09;&#xff0c;右侧是从南向北看的正视图。 输入每个建筑物左下角坐标&#xff08;即x、y坐标的最小值&#xff09;、宽度…

几种基本的高斯分布数学运算,加法、乘法、缩放和卷积及运用场景

文章目录 高斯分布进行乘法运算几种基本的数学运算上述这些运算可以运用与什么场景?高斯分布进行乘法运算 当两个高斯分布进行乘法运算时,这通常是在估计或滤波的上下文中,如在卡尔曼滤波中的更新步骤。为了理解背后的数学原理,我们首先定义两个高斯分布: 当我们将这两个…

介绍Sigmoid函数的平移、平滑和翻转【基于Python可视化分析】

文章目录 简介Sigmoid函数Sigmoid函数曲线调控参数设置python可视化参考 简介 本篇博客介绍了具有S型曲线的Sigmoid函数&#xff0c;以及如何设置、调整Sigmoid函数的参数实现S曲线的平滑、平移和翻转操作。博客给出了Python代码示例&#xff0c;更加深刻形象。&#x1f606;&…