• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
LilyLiya
博客园    首页    新随笔    联系   管理    订阅  订阅
Mongoose virtual / middleware
virtual, .pre, .post

refer to : https://www.udemy.com/course/the-web-developer-bootcamp

帮助文档:middleware:  https://mongoosejs.com/docs/middleware.html

virtuals: https://mongoosejs.com/docs/guide.html#virtuals

 


person.js

const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/shopApp', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log("CONNECTION OPEN!!!") }) .catch(err => { console.log("OH NO ERROR!!!!") console.log(err) }) const personSchema = new mongoose.Schema({ first: String, last: String }) //fullName并不会存在与数据库中,只存在与mongoose, js中 //这种用于我们比较常用而且是可以从数据库中devive出来的信息 //当然我们也可以把它存到数据库中,但是因为它源于数据库,加进去也只是占空间,所以设为virtual personSchema.virtual('fullName').get(function () { return `${this.first} ${this.last}` }) //pre: 在save之前先进行function里面的操作 personSchema.pre('save', async function () { this.first = 'YO'; this.last = 'MAMA'; console.log("ABOUT TO SAVE!!!!") }) //post:save之后进行的操作,比如说现实中,我更改了一个score,然后我需要算一个平均的score,在更改并保存之后。 personSchema.post('save', async function () { console.log("JUST SAVED!!!!") }) const Person = mongoose.model('Person', personSchema);

node person.js

.exit

node -> .load person.js. 

没有save之前,数据库是没有保存信息的

save 之后

因为设置了.pre('save'),save之前只会被改变

posted on 2021-02-10 03:13  LilyLiya  阅读(123)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3