美文网首页
mongoose修饰符

mongoose修饰符

作者: Wrestle_Mania | 来源:发表于2019-12-05 17:03 被阅读0次
    • app.js
    const UserModel = require("./model/user");
    const NewsModel = require("./model/news");
    const BannersModel = require("./model/banners");
    
    // 新增轮播图
    const banners = new BannersModel({
      title: "   程序员是吃青春饭的吗?    ",
      redirect: "http://www.google.com",
      name: "周杰伦"
    });
    
    console.log(banners.name);  // get修饰符只是在这里有用
    
    banners.save(err => {
      if (err) {
        console.log(err);
        return;
      }
      console.log("数据新增成功");
      BannersModel.find({}, (err, docs) => {
        if (err) {
          console.log(err);
          return;
        }
        console.log(JSON.stringify(docs, null, 2));
      });
    });
    
    • model/banners.js
    const mongoose = require("./db");
    
    const BannersSchema = mongoose.Schema({
      title: {
        type: String,
        trim: true //预定义修饰符
      },
      name: {
        type: String,
        get(params) {
          // 自定义修饰符get(不建议使用)
          return `三年一班${params}`;
        }
      },
      redirect: {
        type: String,
        set(params) {
          // 自定义修饰符set
          if (params && !params.includes("http://")) {
            params = `http://${params}`;
          }
          return params;
        }
      },
      status: {
        type: Number,
        default: 1
      }
    });
    
    const BannersModel = mongoose.model("Banners", BannersSchema, "banners");
    
    module.exports = BannersModel;
    

    相关文章

      网友评论

          本文标题:mongoose修饰符

          本文链接:https://www.haomeiwen.com/subject/vsqjgctx.html