Search code examples
node.jsexpressejsmongoose-schema

How can I create a JSON model or schema for express js?


How can I create a JSON model or schema? I want to get the form input to store on local json file. I have some experience with mongoDB. But in this project, I want use a simple json file. I want to store the data like mongoose schema one to a JSON file. How can I achieve that? I'm using NodeJs for backend. EJS for front end.

I already know how store and retrieve data from a JSON file. my question is do I need a schema for a JSON file like mongodb. If it is yes then how to create the schema

import mongoose from "mongoose";

const LoginSchema = new mongoose.Schema({
  email: {
    type: String,
    required: true,
    trim: true,
    validate(value) {
      if (!value.match(/^[^@ ]+@[^@ ]+\.[^@ .]{2,}$/)) {
        throw new Error('Email is not valid.');
      }
    }
  },
  password: {
    type: String,
    required: true,
    trim: true
  },
  userCity: {
    type: String,
  trim: true
  },
  userRegion: {
    type: String,
  trim: true
  },
  userCountry: {
    type: String,
  trim: true
  },
  userPostal: {
    type: String,
  trim: true
  },
  userTimeZone: {
    type: String,
  },
  userAgent: {
    type: String,
  },
});

export default mongoose.model("PP", LoginSchema);

Solution

  • You have to have a json file. Then you have to convert to string the json data. And finally, you can store to json file the data which you converted.

    const FileSystem = require("fs");
    FileSystem.writeFile('file.json', JSON.stringify(yourJsonData), (error) => {
        if (error) throw error;
    });