yoitsro / joigoose Goto Github PK
View Code? Open in Web Editor NEWJoi validation for your Mongoose models without the hassle of maintaining two schemas
License: MIT License
Joi validation for your Mongoose models without the hassle of maintaining two schemas
License: MIT License
Joi got a teeny tiny update... hapijs/joi#2037
At the moment, I don't have bags of time to attempt a refactor of Joigoose. If anybody feels like helping chip away, please let me know. The more, the merrier :)
in express, I saw a module called express-joi
that expose Joi to express architectucture, using the following code
var expressJoi = require('express-joi');
var Joi = expressJoi.Joi
https://www.npmjs.com/package/express-joi
The problem with joigoose is the following, joigoose define a scheme, using the method .meta, that dont exists in native Joi
any help?
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 pathprice.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] }
}
}
}
Very nice module, but I couldn't add middleware to converted mongoose schema. Are you already working on this? Is there any workaround?
I'm using Joi models and using this library to pass them into mongoose, and another library joi-to-swagger to turn my Joi models into definitions - to get references via that library I need to have something like:
var schema = Joi.object.keys().meta({className:'desiredRef'})
but joigoose tries to put that into a model and I get this error from mongoose:
TypeError: Undefined type `Address` at `className`
Did you try nesting Schemas? You can only nest using refs or arrays.
at Function.Schema.interpretAsType (/Users/paul42/code/cb-api/node_modules/mongoose/lib/schema.js:688:11)
at Schema.path (/Users/paul42/code/cb-api/node_modules/mongoose/lib/schema.js:563:29)
at Schema.add (/Users/paul42/code/cb-api/node_modules/mongoose/lib/schema.js:445:12)
at new Schema (/Users/paul42/code/cb-api/node_modules/mongoose/lib/schema.js:99:10)
at Mongoose.model (/Users/paul42/code/cb-api/node_modules/mongoose/lib/index.js:335:14)
at _.each.value (/Users/paul42/code/cb-api/lib/startup/models.js:20:39)
at arrayEach (/Users/paul42/code/cb-api/node_modules/lodash/lodash.js:537:11)
at Function.forEach (/Users/paul42/code/cb-api/node_modules/lodash/lodash.js:9359:14)
at Object.<anonymous> (/Users/paul42/code/cb-api/lib/startup/models.js:17:3)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
is there any easy way to pluck the meta value off the Joi object or clear it out so I can pass the Joi object to Joigoose second
Thanks,
Paul
Versions:
Reproduction Steps:
const Mongoose = require("mongoose")
const Joi = require("joi")
const Joigoose = require("joigoose")(Mongoose)
const schema = Joi.object({
numbers: Joi.array().items(Joi.number())
})
Joigoose.convert(schema)
// TypeError: Undefined type `undefined` at `validate.isAsync`
// Did you try nesting Schemas? You can only nest using refs or arrays.
// at Function.Schema.interpretAsType ([...]/node_modules/mongoose/lib/schema.js:599:11)
// at Schema.path ([...]/node_modules/mongoose/lib/schema.js:456:29)
// at Schema.add ([...]/node_modules/mongoose/lib/schema.js:337:12)
// at Schema.add ([...]/node_modules/mongoose/lib/schema.js:326:14)
// at new Schema ([...]/node_modules/mongoose/lib/schema.js:89:10)
// at Object.internals.typeDeterminer ([...]/node_modules/joigoose/lib/index.js:194:17)
// at Object.internals.convert ([...]/node_modules/joigoose/lib/index.js:116:27)
// at [...]/node_modules/joigoose/lib/index.js:86:37
// at Array.forEach (<anonymous>)
// at Object.internals.convert ([...]/node_modules/joigoose/lib/index.js:84:31)
// at repl:1:10
Increase array conversion test coverage.
Joigoose is not working with Joi Extensions or Custom Types: https://github.com/hapijs/joi/blob/v16/API.md#extensions
Code example:
const Joi = require('@hapi/joi')
const Mongoose = require('mongoose')
const Joigoose = require('joigoose')(Mongoose, { convert: false, abortEarly: false })
// Extending Joi by creating the new types firstname() and lastname()
const JoiExtended = Joi.extend((Joi) => (
// firstname()
{
base: Joi.string().min(2).max(50).trim(),
type: 'firstname'
},
// lastname()
{
base: Joi.string().min(2).max(50).trim(),
type: 'lastname'
}
))
const JoiSchema = JoiExtended.object({
name: JoiExtended.string(),
firstname: JoiExtended.firstname(),
lastname: JoiExtended.lastname(),
email: JoiExtended.email()
})
const MongooseSchema = new Mongoose.Schema(Joigoose.convert(JoiSchema))
const MongooseModel = Mongoose.model('Users', MongooseSchema)
const payload = {
name: 'Guilherme Cruz',
firstname: 'Guilherme',
lastname: 'Cruz',
email: '[email protected]',
}
const result = JoiSchema.validate(payload)
if (result.error) {
console.log('Invalid Schema')
} else {
console.log('Valid Schema')
}
Error:
TypeError: JoiExtended.firstname is not a function
Is it possible to handle virtual fields? There are instances where I want to validate a virtual field and (obviously) not persist it.
How do you set empty objects and arrays with joigoose? Usually when I try to set defaults I don't get any value saved in the mongo database.
var joiUserSchema = Joi.object({
name: Joi.object({
first: Joi.string().required(),
last: Joi.string().required()
}),
email: Joi.string()
.email()
.required(),
bestFriend: Joi.string().meta({
_mongoose: { type: "ObjectId", ref: "User" }
}),
metaInfo: Joi.any(),
addresses: Joi.array()
.items({
line1: Joi.string().required(),
line2: Joi.string()
})
.meta({ _id: false, timestamps: true })
});
var mongooseUserSchema = new Mongoose.Schema(Joigoose.convert(joiUserSchema));
throws:
Schema can only contain plain objects
51 | });
52 |
> 53 | var mongooseUserSchema = new Mongoose.Schema(Joigoose.convert(joiUserSchema));
| ^
54 | User = Mongoose.model("User", mongooseUserSchema);
55 |
56 | /*
at new Object.<anonymous>.module.exports (node_modules/@hapi/hoek/lib/error.js:23:19)
at Object.<anonymous>.module.exports (node_modules/@hapi/hoek/lib/assert.js:20:11)
at Object.<anonymous>.internals.schema (node_modules/@hapi/joi/lib/compile.js:88:5)
at Object.<anonymous>.exports.schema (node_modules/@hapi/joi/lib/compile.js:17:26)
at Object.<anonymous>.internals.Base.$_compile (node_modules/@hapi/joi/lib/base.js:
OS: Arch Linux
npm show joigoose:
[email protected] | MIT | deps: 2 | versions: 34
Joi validation for your Mongoose models without the hassle of maintaining two schemas
https://github.com/yoitsro/joigoose
keywords: joi, mongoose, validation, schema, model, hapi
dist
.tarball: https://registry.npmjs.org/joigoose/-/joigoose-6.2.0.tgz
.shasum: 0d6e4a55da72c4a0531153354c830a6ebbf9df39
.integrity: sha512-amnfYhUqW6fOgRVOwv5a3GKTl4gombFmZlEQpfL3hYnAKbNZ0Dg4T6kadr/y8b8hMWjczHHqOBSUO4nMba30bg==
.unpackedSize: 16.3 kB
dependencies:
@hapi/hoek: ^8.5.0 @hapi/joi: ^16.1.7
maintainers:
- yoitsro <[email protected]>
dist-tags:
latest: 6.2.0
published 3 weeks ago by yoitsro <[email protected]>
npm show mongoose:
[email protected] | MIT | deps: 11 | versions: 564
Mongoose MongoDB ODM
https://mongoosejs.com
keywords: mongodb, document, model, schema, database, odm, data, datastore, query, nosql, orm, db
dist
.tarball: https://registry.npmjs.org/mongoose/-/mongoose-5.8.4.tgz
.shasum: bd35697b2f800bb919c142b1443630fbab382a35
.integrity: sha512-jQjLckUILEQUqBuG+ihjtA9OLmrqcIG5n+vaeHpR++TG8/ug5yy5ogkDnybTSq8Ql5OORud3+OCOc2Uw96q32w==
.unpackedSize: 1.8 MB
dependencies:
bson: ~1.1.1 mongoose-legacy-pluralize: 1.0.2 ms: 2.1.2 sift: 7.0.1
kareem: 2.3.1 mpath: 0.6.0 regexp-clone: 1.0.0 sliced: 1.0.1
mongodb: 3.4.1 mquery: 3.2.2 safe-buffer: 5.1
npm show joi
[email protected] | BSD-3-Clause | deps: 3 | versions: 200
Object schema validation
https://github.com/hapijs/joi
DEPRECATED ⚠️ - This module has moved and is now available at @hapi/joi. Please update your dependencies as this version is no longer maintained an may contain bugs and security issues.
keywords: hapi, schema, validation
dist
.tarball: https://registry.npmjs.org/joi/-/joi-14.3.1.tgz
.shasum: 164a262ec0b855466e0c35eea2a885ae8b6c703c
.integrity: sha512-LQDdM+pkOrpAn4Lp+neNIFV3axv1Vna3j38bisbQhETPMANYRbFJFUyOZcOClYvM/hppMhGWuKSFEK9vjrB+bQ==
.unpackedSize: 192.9 kB
dependencies:
hoek: 6.x.x isemail: 3.x.x topo: 3.x.x
maintainers:
- hueniverse <[email protected]>
dist-tags:
9-beta: 9.0.0-9 latest: 14.3.1 node-0.x: 6.10.1
published a year
joi is leaving the @hapi organization and moving back to 'joi' (https://github.com/sideway/joi/issues/2411)
https://www.npmjs.com/package/@hapi/joi
This breaking change is causing an error for people that already upgraded their dependencies that can't be fixed with package-lock unfortunately as far as i know:
Error: Cannot mix different versions of joi schemas
If
User
name
, andname
is described by child schema joiNameSchema
with a required attribute lastname
,then
name
itself becomes required in User
In other words, here is the desired behavior: if name
is an object, then it must have lastname
, but name
itself should not be required.
Here is a test that fails when inserted into test/index.js
:
it("should deal with objects that have optional properties that have required properties", async () => {
const joiNameSchema = O({
firstname: S(),
lastname: S().required(),
});
const joiUserSchema = O({
name: joiNameSchema, // note that name is not required
});
const mongooseUserSchema = Joigoose.convert(joiUserSchema);
const User = Mongoose.model("User7", mongooseUserSchema);
const newUser = new User({
name: undefined, // since name is not required, this should be OK
});
try {
await newUser.validate();
} catch (err) {
expect(err.message).to.equal(null);
}
});
Hi!
I have the following code
export const joiEmailSchema = Joi.object({
email: Joi.string().meta({ lowercase: true, trim: true })
})
export const joiPersonSchema = Joi.object({ bio: Joi.string() })
import mongoose from 'mongoose'
const Joigoose = require('joigoose')(mongoose)
const mongooseEmailSchema = new mongoose.Schema(Joigoose.convert(joiEmailSchema))
const mongoosePersonSchema = new mongoose.Schema(Joigoose.convert(joiPersonSchema))
mongoosePersonSchema.add({ emails: [mongooseEmailSchema] })
const { email } = req.body
try {
const user = await User.findOne({ _id: req.params.id }).populate('person')
const person = user.person
person.emails.push({ email })
await person.save()
} catch(err) {
// "Person validation failed: bio: Validator failed for path `bio` with value `null`"
}
At the moment of salvation, the biological attribute is becoming null. Why is this happening? This attribute has not been passed, should not be assigned value
export const joiPersonSchema = Joi.object({
bio: Joi.string()
.empty('')
.default('')
})
my question would be this, the null value that was assigned to a non-mandatory attribute
is this right?
While working on a schema, I tried using the Object References in the schema and for some reason, it fails to validate the path that the Object Reference was called.
Here is a snippet of my Schema:
const Joigoose = require("joigoose")(Mongoose);
const Joi = require("@hapi/joi");
const activitySchema = Joi.object({
activityName: Joi.string(),
tasks: Joi.string().meta({ _mongoose: {type: "ObjectId", ref: "Task" } }),
});
const mongooseSchema = new Mongoose.Schema(Joigoose.convert(activitySchema));
module.exports = Mongoose.model("Activity", mongooseSchema);
Error:
[ValidationError]: Activity validation failed: tasks: Cast to ObjectID failed for value "something" at path "tasks"
Error:
MongooseError [CastError]: Cast to ObjectID failed for value "something" at path "tasks"
Like in mongoose that allows developers to provide enum validator like this:
var personSchema = new Schema({ .... gender: { type: String, enum: ['F', 'M'] } });
It's not possible to create compound index like
schema.index({ locationId: 1, date: 1 }, { unique: true })
Example:
const Joi = require('joi')
const mongoose = require('mongoose')
const joigoose = require('joigoose')
const Joigoose = joigoose(mongoose)
const joiObject = Joi.object().keys({
optional: Joi.object().keys({
requiredProperty: Joi.string().required()
}),
otherProperty: Joi.string().required()
})
const Model = mongoose.model('course', Joigoose.convert(joiObject) )
const objectToBeValidated = {
// optional: { requiredProperty: 'test' },
otherProperty: 'test'
};
joiObject.validate(objectToBeValidated); // works fine
( new Model(objectToBeValidated) ).validate(); // throw validation error
Expected result: should be a valid object
.
PS: thanks for the lib, it's awesome! 😄
JOI has a language.js that has meaningful error messages.
I don't know how deep joigoose works for converting schemas to the ones compatible with mongoose but I am having this problem where my joi schema is kinda valid (cause it did not throw me any error) but when I try to use the joigoose convert method he does not work at all. For my other schemas, it works fine but in this specific case doesn't.
const Joi = require('joi');
const mongoose = require('mongoose');
const Joigoose = require('joigoose')(mongoose);
const item = Joi.object().keys({
id: Joi.string(),
label: Joi.string(),
type: Joi.string(),
listIds: Joi.array(),
});
const autocomplete = Joi.array().items(item);
const where = {
restrictions: {
content: Joi.array().items(autocomplete).allow(null),
},
};
const schema = {
where: Joi.array().items(where),
};
console.log(Joigoose.convert(schema));
TypeError: Invalid schema configuration: undefined is not a valid type within the array restrictions.content.See http://bit.ly/mongoose-schematypes for a list of valid schema types.
This is a sample of valid data:
const valid = {
where: [
{
restrictions: {
content: [
[{
id: '123',
label: 'a',
type: 'product',
}],
[{
id: '1234',
label: 'b',
type: 'tag',
}],
],
},
},
],
};
Error: Cannot mix different versions of joi schemas
at Object. (.\index.js:11:43)
Source:
const Mongoose = require("mongoose")
const Schema = Mongoose.Schema
const Joigoose = require("joigoose")(Mongoose)
const Joi = require("@hapi/joi")
const joiProductSchema = Joi.object({
model: Joi.string().alphanum().min(2).max(255).trim().required(),
brand: Joi.string().alphanum().min(2).max(255).trim().required(),
price: Joi.number().positive(),
photo: Joi.string().max(255).trim()
})
const ProductSchema = new Schema(Joigoose.convert(joiProductSchema))
From this code:
Joi.array().items({ foo: Joi.string() })
I get this error: Cannot read property '$__' of undefined (500)
But this works ok.
Joi.array().items(Joi.string())
My issue arises with Joi.date
in combination with Joi.in
and I think it is a bug, but correct me if I am doing something wrong.
const schema = Joi.object().keys({
dates: Joi.array().items(Joi.date()),
assignedOn: Joi.date().allow(Joi.in('dates'), null).default(null)
});
It seems to me that the mongoose is not validating the given object correctly
This is my full Test Script I wrote to further evaluate this issue:
const Joi = require('joi');
const mongoose = require('mongoose');
const connect = connectionString => {
console.log(`Connect to MongoDB: ${ connectionString }`);
const connection = mongoose.createConnection(`mongodb://${ connectionString }`, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
connection.then(() => {
console.log('Connected correctly to MongoDB.');
});
connection.catch(err => {
console.log('Connection error to MongoDB');
console.error(error);
});
return connection
}
const connection = connect('localhost/tmp');
const Joigoose = require('joigoose')(connection);
const test = async function () {
console.log('Start Test')
const schema = Joi.object().keys({
dates: Joi.array().items(Joi.date()),
assignedOn: Joi.date().allow(Joi.in('dates'), null).default(null)
});
const obj = {
"dates": [
"2021-02-09 16:00"
],
"assignedOn": "2021-02-09 16:00"
};
// No Error
const joiResult = schema.validate(obj);
console.log('joiResult:', joiResult);
console.log(
'Test if `assignedOn` is included in `dates`:',
joiResult.value.dates.includes(joiResult.value.assignedOn)
);
const Model = connection.model('Model', Joigoose.convert(schema));
const instance = new Model(joiResult.value);
try {
// Error
await instance.save()
console.log('Instance saved.');
console.log(instance)
} catch (error) {
console.error(error);
}
}
Promise.all([connection]).then(test).finally(() => process.exit(0));
Connect to MongoDB: localhost/tmp
Connected correctly to MongoDB.
Start Test
joiResult: {
value: {
dates: [ 2021-02-09T15:00:00.000Z ],
assignedOn: 2021-02-09T15:00:00.000Z
}
}
Test if `assignedOn` is included in `dates`: true
Error: Model validation failed: assignedOn: Validator failed for path `assignedOn` with value `Tue Feb 09 2021 16:00:00 GMT+0100 (Central European Standard Time)`
at ValidationError.inspect (PATH_TO_MY_PROJECT/node_modules/mongoose/lib/error/validation.js:47:26)
at formatValue (node:internal/util/inspect:735:19)
at inspect (node:internal/util/inspect:309:10)
at formatWithOptionsInternal (node:internal/util/inspect:1967:40)
at formatWithOptions (node:internal/util/inspect:1849:10)
at console.value (node:internal/console/constructor:330:14)
at console.warn (node:internal/console/constructor:363:61)
at test (PATH_TO_MY_PROJECT/test.js:62:17)
at processTicksAndRejections (node:internal/process/task_queues:93:5) {
errors: {
assignedOn: ValidatorError: Validator failed for path `assignedOn` with value `Tue Feb 09 2021 16:00:00 GMT+0100 (Central European Standard Time)`
at validate (PATH_TO_MY_PROJECT/node_modules/mongoose/lib/schematype.js:1256:13)
at PATH_TO_MY_PROJECT/node_modules/mongoose/lib/schematype.js:1231:24
at processTicksAndRejections (node:internal/process/task_queues:93:5) {
properties: [Object],
kind: 'user defined',
path: 'assignedOn',
value: 2021-02-09T15:00:00.000Z,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
}
},
_message: 'Model validation failed'
}
Do you need more information from me? I appreciate any help with this.
Hi,
How we implement joigoose with ES6 this part : var Joigoose = require('joigoose')(Mongoose);
like
import joigoose from 'joigoose'
joigoose(Mongoose);
or something else ?
I see your homepage documentation you can create an objectId reference
bestFriend: Joi.string().meta({
_mongoose: { type: "ObjectId", ref: "User" },
}),
How would you build an array of ObjectId references using joigoose?
bestFriends: Joi.array().items(Joi.string().meta({
_mongoose: {type: "ObjectId", ref: "User"},
})),
Because my populate isn't working. Trying to see if this is correct syntax first before I investigate Mongoose.
I'd like to have the error from Joi pass into my mongoose validator
Hi guys,
I tried to use the joigoose with dynamoose but when I try to convert the schema generated by, dynamoose keep sending the same error Validation failed:
Here's my test
const dynamoose = require('dynamoose');
const joigoose = require('joigoose');
const Joi = require('joi');
dynamoose.local('http://localhost:8083');
dynamoose.AWS.config.update({
accessKeyId: 'secret',
secretAccessKey: 'secret',
region: 'us-east-1',
});
dynamoose.setDefaults({
create: true,
});
const schema = Joi.object().keys({
id: Joi.string().required(),
status: Joi.string(),
});
const entrySchema = joigoose(dynamoose).convert(schema);
const EntryModel = dynamoose.model('Entry', entrySchema);
const entry1 = new EntryModel({ id: 'someId', status: 'status-one'});
entry1.save(e => {
if (e) {
console.log('some error: ', e);
} else {
console.log('no error');
}
and sends this as output,
$ node index.js
some error: { ValidationError: Validation failed: id
at Attribute.toDynamo (/Users/javiercastro/Documents/projects/ex/joigoose/node_modules/dynamoose/lib/Attribute.js:352:11)
at Schema.toDynamo (/Users/javiercastro/Documents/projects/ex/joigoose/node_modules/dynamoose/lib/Schema.js:162:25)
at NewModel.Model.put (/Users/javiercastro/Documents/projects/ex/joigoose/node_modules/dynamoose/lib/Model.js:286:20)
at Object.<anonymous> (/Users/javiercastro/Documents/projects/ex/joigoose/index.js:26:8)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12) name: 'ValidationError', message: 'Validation failed: id' }
✨ Done in 0.31s.
but if I did the same with pure dynamoose validation it works
code
const dynamoose = require('dynamoose'), Schema = dynamoose.Schema;
// Configuration to dynamoose local
dynamoose.local('http://localhost:8083');
dynamoose.AWS.config.update({
accessKeyId: 'secret',
secretAccessKey: 'secret',
region: 'us-east-1',
});
dynamoose.setDefaults({
create: true,
});
const schema = new Schema({
id: {
type: String,
required: true
},
status: {
type: String
}
});
const EntryModel = dynamoose.model('Entry', schema);
const entry1 = new EntryModel({ id: 'someId', status: 'status-one'});
entry1.save(e => {
if (e) {
console.log('some error: ', e);
} else {
console.log('no error');
}
});
output
$ node index.js
no error
✨ Done in 0.34s.
even the validation works if I don't specify an Id
some error: { ValidationError: Required value missing: id
at Attribute.toDynamo (/Users/javiercastro/Documents/projects/ex/joigoose/node_modules/dynamoose/lib/Attribute.js:337:13)
at Schema.toDynamo (/Users/javiercastro/Documents/projects/ex/joigoose/node_modules/dynamoose/lib/Schema.js:162:25)
at NewModel.Model.put (/Users/javiercastro/Documents/projects/ex/joigoose/node_modules/dynamoose/lib/Model.js:286:20)
at Object.<anonymous> (/Users/javiercastro/Documents/projects/ex/joigoose/index.js:38:8)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
name: 'ValidationError',
message: 'Required value missing: id' }
thanks
Hi,
I have a problem with joigoose convertion to mongoose schema with the usage of subCollection.
Basically, mongoose add, in subCollection element, an automated _id
attribute and, in most cases, I don't want this.
In mongoose schema, to stop this, I have this code :
var fieldsSchema = mongoose.Schema({
d : { type : Date }, // Date
sa : [ { type : String } ],
}, { _id : false, autoIndex : false });
var schema = mongoose.Schema({
f : [ fieldsSchema ]
});
It's possible for the Joi.array()
to add the mongoose schema options in meta ?
This is the list of all possibly options : https://www.quora.com/What-are-all-the-options-that-can-be-used-when-creating-a-mongoose-schema-for-mongodb
"joi": "^14.3.1"
"joigoose": "^4.0.4"
"mongoose": "^5.4.19"
Upon validation I receive the error ""url" is not allowed to be empty". Below is my schema. I added .optional() to the field as well but I get the same error.
export const jBusinessSchema = Joi.object({
name: Joi.string().min(3).max(50).required(),
url: Joi.string().uri().optional(),
sections: Joi.array().items(Joi.string().meta({ type: 'ObjectId', ref: 'Section' })),
types: Joi.array().items(Joi.string().meta({ type: 'ObjectId', ref: 'Type' })),
categories: Joi.array().items(Joi.string().meta({ type: 'ObjectId', ref: 'Category' }))
}).options({ stripUnknown: true });
Validation code:
export class BusinessValidator extends BaseValidator {
public validate(): any {
return (req: Request, res: Response, next: NextFunction) => {
Joi.validate(req.body, jBusinessSchema)
.then(data => { next(); })
.catch((err: Joi.ValidationError) => {
return res.status(422).json({ message: cleanErr(err) });
});
};
}
}
Hi,
I have this error on document save with a schema generate by joigoose
:
DeprecationWarning: Implicit async custom validators (custom validators that take 2 arguments) are deprecated in mongoose >= 4.9.0. See http://mongoosejs.com/docs/validation.html#async-custom-validators for more info.
Code and Lab will need to be updated to the latest versions. They target >= Node 4 so anyone still using < Node 4, tough luck. This will require a major bump.
Also, the latest version of Mongoose should be used.
I don't think the changes in 4eba3f9 have the intended result, as any Joi schema with .unknown will end up as a single Mongoose property with type mixed, and children will not be processed due to early return on line #82.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.