Day 29 of egg learning notes: using mongoose in eggjs

Keywords: Front-end Mongoose Database MongoDB

1, Mongoose in egg

1. Installing mongoose in an egg project

cnpm i mongoose --save

2. Configure the eg mongoose plug-in in config > plugin.js

exports.mongoose = {
  enable: true,
  package: "egg-mongoose"
};

3. Configure the database connection address in config > config.default.js

config.mongoose = {
    client: {
      // url: "mongodb://eggadmin:123456@localhost:27017/eggcms", / / with user name and password
      url: "mongodb://127.0.0.1/eggcms ", / / no username and password
      options: {}
    }
  };

4. Create a new model folder under the app folder, which contains the database table model food and food table. (food table)

module.exports = app => {
  const mongoose = app.mongoose; // Introduce mongoose to establish connection
  const Schema = mongoose.Schema;

  // Database table mapping
  const FoodSchema = new Schema({
    foodName: { type: String }, // Food name
    foodPrice: { type: Number }, // Food price (Jin)
    foodColor: { type: String }, // Food color
    foodSeason: { type: String } // Food season
  });

  return mongoose.model("Food", FoodSchema, "food");
};

5. Define two routes: one is to query food table data, and the other is to add food table data.

"use strict";

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  router.get("/", controller.home.index);

  router.get("/findFood", controller.home.findFood);

  router.get("/addFood", controller.home.addFood);
};

6. Method in controller:

"use strict";

const Controller = require("egg").Controller;

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.body = "hi, egg";
  }
  // Check food list
  async findFood() {
    const { ctx } = this;
    var result = await ctx.service.food.getFoodList();
    console.log(result);
    ctx.body = result;
  }
  // Add food table
  async addFood() {
    const { ctx } = this;
    var food = new ctx.model.Food({
      foodName: "Fried Steamed Rice", // Food name
      foodPrice: 12, // Food price (Jin)
      foodColor: "white", // Food color
      foodSeason: "Four seasons" // Food season
    });
    var result = await food.save();
    ctx.body = result;
  }
}

module.exports = HomeController;

7. New food.js in service

const Service = require("egg").Service;

class FoodService extends Service {
  async getFoodList() {
    // Querying the data in the food table
    return await this.ctx.model.Food.find({});
  }
}

module.exports = FoodService;

8. Continuous access to addFood provides a response:

 

9. Access the findFood path to find the data in the comparison table:

 

10. In the definition of a delete, a modified route

"use strict";

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  router.get("/", controller.home.index);

  router.get("/findFood", controller.home.findFood);

  router.get("/addFood", controller.home.addFood);

  router.get("/editFood", controller.home.editFood);

  router.get("/deleteFood", controller.home.deleteFood);
};

11. Controller write:

"use strict";

const Controller = require("egg").Controller;

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.body = "hi, egg";
  }
  // Check food list
  async findFood() {
    const { ctx } = this;
    var result = await ctx.service.food.getFoodList();
    console.log(result);
    ctx.body = result;
  }
  // Add food table
  async addFood() {
    const { ctx } = this;
    var food = new ctx.model.Food({
      foodName: "Stir fried Drawstring", // Food name
      foodPrice: 22, // Food price (Jin)
      foodColor: "yellow", // Food color
      foodSeason: "Four seasons" // Food season
    });
    var result = await food.save();
    ctx.body = result;
  }
  // Add food table
  async editFood() {
    const { ctx } = this;
    var result = await this.ctx.model.Food.updateOne(
      {
        foodName: "Stir fried Drawstring"
      },
      {
        foodName: "Lanzhou hand-pulled noodles", // Food name
        foodPrice: 8, // Food price (Jin)
        foodColor: "white", // Food color
        foodSeason: "summer" // Food season
      },
      function(err, result) {}
    );
    ctx.body = result;
  }
  // Add food table
  async deleteFood() {
    const { ctx } = this;
    var result = await this.ctx.model.Food.deleteOne({
      foodName: "Lanzhou hand-pulled noodles"
    });
    ctx.body = result;
  }
}

module.exports = HomeController;

12. Execute edit food to get: stir fried noodles become Lanzhou noodles

 

13. Visit deleteFood to get: the data of Lanzhou Ramen was deleted successfully

 

The above is a simple demo of adding, deleting, modifying and querying data using egg mongoose

Posted by abisai on Mon, 11 May 2020 10:12:07 -0700