Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

mongoose model and joi validation

const mongoose = require("mongoose");
const Joi = require("joi");
Joi.objectId = require("joi-objectid")(Joi);

const { Schema } = mongoose;

const postSchema = new Schema(
  {
    userId: {
      type: mongoose.Schema.ObjectId,
      ref: "user",
    },
    name: {
      type: String,
    },
    description: {
      type: String,
    },
    recipeStepValue: {
      type: Array,
    },
    setpsCount: {
      type: String,
    },
    postType: {
      type: String,
    },
    image: [
      {
        type: String,
      },
    ],
    location: {
      fullAddress: {
        type: String,
      },
      address: {
        type: String,
      },
      postAddress: {
        type: String,
      },
      city: {
        type: String,
      },
      state: {
        type: String,
      },
      country: {
        type: String,
      },
      postcode: {
        type: String,
      },
      longitude: {
        type: Number,
      },
      latitude: {
        type: Number,
      },
    },
    video: [
      {
        type: String,
      },
    ],
    mediaFiles: [{ type: String }],
    tags: {
      type: Array,
    },
    difficulty: {
      type: String,
    },
    comments: {
      type: mongoose.Schema.ObjectId,
      ref: "comment",
    },
    likes: { type: mongoose.Schema.ObjectId, ref: "likes" },
    ingredient: [
      {
        fdcId: String,
        label: String,
      },
    ],
    ingredients: [
      {
        id: {
          type: mongoose.Schema.ObjectId,
          ref: "ingredients",
        },
        quantity: { type: String },
        unit: { type: String },
      },
    ],
  },

  {
    timestamps: true,
  }
);
const Post = mongoose.model("post", postSchema);
const validatePost = (post) => {
  const schema = {
    userId: Joi.objectId().required(),
    description: Joi.any(),
    imageFile: Joi.any(),
    name: Joi.any(),
    location: Joi.any(),
    difficulty: Joi.string(),
    postType: Joi.string(),
    ingredient: Joi.any(),
    tags: Joi.any(),
  };
  return Joi.validate(post, schema);
};

module.exports.Post = Post;
module.exports.validatePost = validatePost;
Source by gist.github.com #
 
PREVIOUS NEXT
Tagged: #mongoose #model #joi #validation
ADD COMMENT
Topic
Name
3+5 =