【NodeJS】NodeJS+mongoDB在线版开发简单RestfulAPI (七):MongoDB的设置

server/2024/10/23 10:05:43/

本项目旨在学习如何快速使用 nodejs 开发后端api,并为以后开展其他项目的开启提供简易的后端模版。(非后端工程师)
由于文档是代码写完之后,为了记录项目中需要注意的技术点,因此文档的叙述方式并非开发顺序(并非循序渐进的教学文档)。建议配合项目源码node-mongodb-template 。

【NodeJS】NodeJS+mongoDB在线版开发简单RestfulAPI (一):项目简介及安装依赖

【NodeJS】NodeJS+mongoDB在线版开发简单RestfulAPI (二):项目文件夹架构及路由的设置

【NodeJS】NodeJS+mongoDB在线版开发简单RestfulAPI (三):Cors的设置及.env文件的设置

【NodeJS】NodeJS+mongoDB在线版开发简单RestfulAPI (四):状态码的使用

【NodeJS】NodeJS+mongoDB在线版开发简单RestfulAPI (五):POST上传文件的设置

【NodeJS】NodeJS+mongoDB在线版开发简单RestfulAPI (六):token的设置

【NodeJS】NodeJS+mongoDB在线版开发简单RestfulAPI (七):MongoDB的设置

【NodeJS】NodeJS+mongoDB在线版开发简单RestfulAPI (八):API说明(暂时完结,后续考虑将在线版mongoDB变为本地版)

MongoDB的设置

选择了MongoDB的在线版数据库,可以申请免费的空间使用,点击网址申请。申请和创建库之后,复制针对nodejs提供的code,如下

mongodb+srv://db:<db_password>@test.gx6wc.mongodb.net/?retryWrites=true&w=majority&appName=test

将其中<db_password>替换成你设置的密码。

接下来就可以在nodejs中使用该云数据库了。

连接数据库

  • 安装依赖

pnpm i --save mongoose

  • 引用依赖
//app.js
const mongoose = require('mongoose');
  • 连接数据库
mongoose.connect('mongodb+srv://db:'
+process.env.MONGO_ATLAS_PW
+'@test.gx6wc.mongodb.net/?retryWrites=true&w=majority&appName=test');mongoose.Promise = global.Promise;

mongoose API学习

Model数据结构声明
Type数据类型
  • mongoose.Schema.Types.ObjectId 自动生成的id;
  • Number 数字型;
  • String 字符串型;
required:是否必要
default:默认值
ref:关联的表/数据结构/model
unique:是否唯一
match:数据正则检查匹配
定义数据结构

mongoose.Schema({...})

mongoose.model('<modelName>', <ModelSchema>)

//product.js
const mongoose = require('mongoose');const productSchema = mongoose.Schema({_id:mongoose.Schema.Types.ObjectId,name:{type:String, required:true},price:{type:Number, required:true},productImage:{type:String, required:true},
})module.exports = mongoose.model('Product', productSchema);
//order.js
const mongoose = require('mongoose');const orderSchema = mongoose.Schema({_id:mongoose.Schema.Types.ObjectId,//product的值为ObjectId,与【Product】关联product:{type:mongoose.Schema.Types.ObjectId, required:true,ref:'Product'},quantity:{type:Number, default:1},
})module.exports = mongoose.model('Order', orderSchema);
//user.js
const mongoose = require('mongoose');const userSchema = mongoose.Schema({_id:mongoose.Schema.Types.ObjectId,email:{type:String, required:true,unique:true,//校验email的格式match:/(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/},password:{type:String, required:true},
})module.exports = mongoose.model('User', userSchema);
数据操作
类型引用
//product Model定义的位置
const Product = require('../models/product');
exec: 执行

执行mongoose的query操作后,调用exec()方法;

Product.find().then();
Product.find().exec().then();

区别在于: mongoose 的所有查询操作返回的结果都是 query (官方文档是这样写的),并非一个完整的promise。
而加上.exec()则将会返回成为一个完整的 promise 对象,但是其是 mongoose 自行封装的 promise ,与 ES6 标准的 promise 是有所出入的(你应该会在控制台看到相关的警告),而且官方也明确指出,在未来的版本将会废除自行封装的promise,改为 ES6 标准,因此建议楼主在使用过程中替换为 ES6 的 promise,如下:

const mongoose = require(‘mongoose’);
mongoose.Promise = global.Promise;

find: 查询
//查询全部
Product.find();
Product.find().exec().then(docs=>{//docs是products数组
});//查找所有满足条件的数据
//条件格式 {prop:value,...}
User.find({email: req.body.email}).exec().then(docs=>{//docs是数组
})//查询满足条件的数据中的第一个
Product.findOne();
User.findOne({email: req.body.email}).exec().then(doc=>{//doc是一个对象
})//查询指定Id的数据(id唯一)
Product.findById();
Product.findById(id).exec().then(doc=>{//doc是一个对象
})Product.findOneAndDelete();
Product.findOneAndReplace();
Product.findOneAndUpdate()
where: 查询条件
Product.where({email: req.body.email}).fineOne().exec().then(doc=>{});
select: 指定属性
//Product包含属性:name, price, _id//需求是只显示name和price
Product.find().select('name price').exec().then(docs=>{//docs是products数组
});
populate: 子表属性
//Order包含属性:product quantity _id
//product是子表数据的_id//需求是显示product的详细属性
Order.find().select('product quantity').populate('product','name price').exec().then(docs=>{});
//{
//  product:{
//    name:"",
//    price:11
//  },
//  quantity:1,
//}
save: 新增
const product = new Product({_id:new mongoose.Types.ObjectId(),name:req.body.name,price:req.body.price,productImage:req.file.path});
product.save().then(result=>{//result和product实例相同})
updateOne: 修改
const updateOpts = {name:"",price:22,
};
//找到指定id的数据,并修改对应字段
Product.updateOne({_id:id},{$set:updateOpts}).exec().then(result=>{      
})
deleteOne: 删除
Product.deleteOne({_id:id}).exec().then(result=>{     
})

http://www.ppmy.cn/server/134146.html

相关文章

3D虚拟服装试穿技术:迈向元宇宙与AR电商的新时代

随着电子商务的不断进化,消费者对于在线购物体验的需求也在不断提升。在这样的背景下,3D虚拟服装试穿技术正逐渐成为连接现实世界与数字世界的桥梁,为用户带来前所未有的沉浸式购物体验。本文将介绍一种创新的3D虚拟服装试穿系统——GS-VTON,它旨在克服现有技术局限,并提供…

Flutter Container组件

Over the past few years, I’ve been fortunate to collaborate with interior designers, and there’s a distinct flair to their approach to crafting captivating interiors. It’s not just about arranging furniture randomly; they meticulously plan layouts, sele…

液态神经网络 LNN

神经网络 (NN) 是 机器学习 模仿人脑结构和运算能力以从训练数据中识别模式的算法。 通过处理和传输信息的互连人工神经元网络&#xff0c;神经网络可以执行复杂的任务&#xff0c;例如 人脸识别, 自然语言理解&#xff0c;以及无需人工协助的预测分析。 尽管神经网络是一种强…

context.getExternalFilesDir()与返回的路径对照 Android 存储路径

从Android 10开始&#xff0c;对于数据访问权限要求的越来越严&#xff0c;app对于私有目录的使用越来越多&#xff0c;进而对context.getExternalFilesDir()的使用也多了&#xff0c;下面是对应传不同参获取的返回路径&#xff1a; getExternalCacheDir(); 路径为&#xff…

20240818 字节跳动 笔试

文章目录 1、编程题1.11.21.31.4岗位:BSP驱动开发工程师-OS 题型:4 道编程题 1、编程题 1.1 小红的三消游戏: 小红在玩一个三消游戏,游戏中 n 个球排成一排,每个球都有一个颜色。若有 3 个颜色相同的球连在一起,则消除这 3 个球,然后剩下的球会重新连在一起。在没有 …

知识问答网站毕业设计基于SpringBootSSM框架

计算机毕业设计/springboot/javaWEB/J2EE/MYSQL数据库/vue前后分离小程序 目录 一、摘要 二、概述 2.1 开发背景 2.2开发目标 三、需求设计 3.1 主要研究内容 3.2 功能描述 3.3 功能图展示 3.4 主要开发技术 四、总结 一、摘要 随着互联网的飞速发展和信息时代的到…

SQL语句高级查询(适用于新手)

SQL查询语句的下载脚本链接&#xff01;&#xff01;&#xff01; 【免费】SQL练习资源-具体练习操作可以查看我发布的文章资源-CSDN文库https://download.csdn.net/download/Z0412_J0103/89908378 本文旨在为那些编程基础相对薄弱的朋友们提供一份详尽的指南&#xff0c;特别聚…

第十六届蓝桥杯嵌入式真题

蓝桥杯嵌入式第十二届省赛真题二 蓝桥杯嵌入式第十三届省赛真题一 蓝桥杯嵌入式第十三届省赛真题二 蓝桥杯嵌入式第十四届省赛真题 蓝桥杯嵌入式第十四届模拟考试一 蓝桥杯嵌入式第十四届模拟考试二 蓝桥杯嵌入式第十五届模拟考试一 蓝桥杯嵌入式第十五届模拟考试二 蓝…