当前位置: 首页 > article >正文

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

本项目旨在学习如何快速使用 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.kler.cn/news/365849.html

相关文章:

  • Golang | Leetcode Golang题解之第503题下一个更大元素II
  • 找不到包的老版本???scikit-learn,numpy,scipy等等!!
  • 【揭秘】图像算法工程师岗位如何进入?
  • 软考(中级-软件设计师)计算机系统篇(1024)
  • 【Javaee】网络原理—TCP协议的核心机制
  • 【Vispy库】一个用于高性能交互式2D/3D数据可视化库 Python库
  • 虚拟化基础
  • java List<Map<String, Object>> 转 List<JSONObject> 的几种方式
  • Log4j和SLF4J在Java中打印日志的区别
  • Node.js是什么? 能做什么?
  • Harmony 开发与H5进行交互
  • OneNote不能拖动页面解决方案
  • docker-compose安装sentinel
  • Springcloud健身小程序-计算机毕业设计源码27368
  • linux中级wed服务器(https搭建加密服务器)
  • Spring Boot 中应用单元测试(UT):结合 Mock 和 H2 讲解和案例示范
  • (11)(2.1.7) FETtec OneWire ESCs(一)
  • idea git 一些日常操作解决办法(Git撤销回滚操作)
  • 【C语言】控制台学生成绩管理系统
  • 关系型数据库(1)----MySQL(初阶)
  • 大数据-189 Elasticsearch - ELK 日志分析实战 - 环境配置启动 Nginx、ZK、Kafka、ES、Kibana
  • OpenCV视觉分析之运动分析(4)背景减除类:BackgroundSubtractorKNN的一系列set函数的使用
  • 前端-基础CSS 知识总结
  • 六,Linux基础环境搭建(CentOS7)- 安装HBase
  • Python与MySQL
  • 3.添加缓存和缓存更新策略