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

Time:09-27

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);

CodePudding user response:

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;
});

CodePudding user response:

I guys I got the solution. I used mongoose schema or model to store the JSON data to JSON files. I just skipped Id from mongoose and it working perfect. Why I skipped the id from schema because of I create the id's with other packages. Here is the code.

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,
    }
  },
  { _id: false }
);

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