Day 25 of egg learning notes: mongoose predefined pattern modifiers Getters and Setters custom modifiers

1, mongoose predefined pattern modifier.

lowercase,uppercase,trim

The predefined pattern modifiers provided by mongoose can format our added data.

① , create new news.js under the db folder, connect to the database, and export newsModel.

var mongoose = require("./db.js");
// Define data table (Collection) mapping, note: field names must be consistent with the database
var NewsSchema = mongoose.Schema({
  title: String,
  author: String,
  pic: String,
  content: String,
  status: {
    type: Number,
    dafault: 1
  }
});

module.exports = mongoose.model("News", NewsSchema, "news");

② Create new news.js, and type the following code

var NewsModel = require("./model/news.js");
var news = new NewsModel({
  title: "    I am an international news    ",
  author: "Zhang San",
  pic: "http://xxx.com/x.png",
  cintent: "I'm a content 11"
});

news.save(function(err) {
  if (err) {
    console.log(err);
    return;
  }
  NewsModel.find({}, function(err, docs) {
    if (err) {
      console.log(err);
      return;
    }
    console.log(docs);
  });
});

It can be seen that the title field has blank spaces before and after.

Change the definition field to the following writing method, and use trim.

In the execution of news.js, the data title of the warehousing operation has processed the blank cells before and after.

 

2, Mongoose

Getters and Setters custom modifiers

In addition to the built-in modifiers of mongoose, we can also format the data when adding data through the set (recommended) modifier. You can also get (not recommended) to format the data when the instance gets the data.

get and set functions are formatted when data is stored or read. The url does not have http: / / plus http://


 

var mongoose = require("./db.js");
// Define data table (Collection) mapping, note: field names must be consistent with the database
var NewsSchema = mongoose.Schema({
  // title: String,
  title: {
    type: String,
    trim: true
  },
  url: {
    type: String,
    set(url) {
      if (!url) return url;
      if (url.indexOf("http://") != 0 && url.indexOf("https://") != 0) {
        url = "http://" + url;
      }
      return url;
    },
    get: function(url) {
      if (!url) return url;

      if (url.indexOf("http://") != 0 && url.indexOf("https://") != 0) {
        url = "http://" + url;
      }
      return url;
    }
  },
  author: String,
  pic: String,
  content: String,
  status: {
    type: Number,
    dafault: 1
  }
});

module.exports = mongoose.model("News", NewsSchema, "news");

Sleep?

Tags: Front-end Mongoose Database

Posted on Sun, 03 May 2020 22:13:59 -0400 by kyberfabrikken