zoukankan      html  css  js  c++  java
  • Mongoose virtual / middleware

    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之前只会被改变

  • 相关阅读:
    safeNet
    网店
    微信公众号自定义菜单与回车
    西游记对教育的启发
    zencart资源
    cmd批处理常用符号详解
    div垂直居中
    git工作量统计
    VS2012变化的快捷键:
    sql 树 递归
  • 原文地址:https://www.cnblogs.com/LilyLiya/p/14394870.html
Copyright © 2011-2022 走看看