yoitsro / joigoose

Joi validation for your Mongoose models without the hassle of maintaining two schemas
MIT License
177 stars 19 forks source link

Nested schemas & default values #39

Closed adamalfredsson closed 4 years ago

adamalfredsson commented 4 years ago

Does joigoose support nested schemas? I'm not successful in making it work:

import mongoose from 'mongoose';
const Joigoose = require('joigoose')(mongoose);

const PriceSchema = Joi.object().keys({
  amount: Joi.number(),
  currency: Joi.string()
});

const ProductSchema = Joi.object({
  title: Joi.string().required(),
  price: PriceSchema.optional()
    .default(function() {
      return { amount: 100, currency: 'USD' };
    })
});

const mongooseProductSchema = new mongoose.Schema(Joigoose.convert(ProductSchema));

The schema output:

{
  title: {
    validate: { validator: [Function: bound ] AsyncFunction },
    required: true,
    type: [Function: String]
  },
  price: {
    default: [Function],
    amount: { validate: [Object], type: [Function: Number] },
    currency: { validate: [Object], type: [Function: String] }
  }
}

Mongoose throws the following error:

TypeError: Invalid schema configuration: undefined is not a valid type at path price.default. See http://bit.ly/mongoose-schematypes for a list of valid schema types.

Expected output(?):

{
  title: {
    validate: { validator: [Function: bound ] AsyncFunction },
    required: true,
    type: [Function: String]
  },
  price: {
    default: [Function],
    type: {
      amount: { validate: [Object], type: [Function: Number] },
      currency: { validate: [Object], type: [Function: String] }
    }
  }
}
yoitsro commented 4 years ago

Hey @nomadoda. I've not had a chance to look into this yet because of other commitments, but is this something you could possibly add as a test case into the test suite and double check to see if it works there?

yoitsro commented 4 years ago

@nomadoda I'm going to close this since I've had no response from you in a while. Feel free to reopen it if you get a chance to look at it again.