Mongoose, bodymen and pre validate a collection ref
francisrod01 opened this issue · 2 comments
francisrod01 commented
Hi there! A have a question about mongoose
and pre validate.
Is it possible to pre validate the request using Mongoose and bodymen and schema.tree
with reference other collection as a field?
.
I need to validate the "user" and "location" fields.
import { Router } from 'express';
import { middleware as body } from 'bodymen';
import { token } from '../../services/passport';
import { create } from './controller';
import Company, { schema } from './model';
const router = new Router();
const {
user,
social_name,
...
location,
...
} = schema.tree;
router.post('/',
token({ required: true }),
body({
user,
...
location,
...
}),
create);
export default router;
The company model:
import mongoose, { Schema } from 'mongoose';
import mongooseKeywords from 'mongoose-keywords';
const statusList = ['a', 'd'];
const CompanySchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true,
},
social_name: {
type: String,
trim: true,
default: null,
},
fantasy_name: {
type: String,
trim: true,
...
location: {
type: Schema.Types.ObjectId,
ref: 'Location',
required: true,
},
...
}
In the location
field, if I POST a JSON object, it process like that:
{
"formatted_address": "RN143, Mendoza, Argentina",
"id": "5ba416cb667...",
"name": "Ruta Nacional 143",
"place_id": "C_EhlSTjE0MywgTWVuZ..."
}
And shows me an error as below:
ValidationError: location: Cast to ObjectID failed for value "[object Object]" at path "location", user: Path `user` is required.
diegohaz commented
Hey Francis.
It's not current supported that way. You can try to use other schemas though:
import { schema as userSchema } from "../user/model";
import { schema as locationSchema } from "../location/model";
body({
user: userSchema.tree,
location: locationSchema.tree
});
I'm not sure if that works as I've never used that approach. Let me know if it works for you. :)
francisrod01 commented
I hope it will be supported soon.
For the moment, I'm using body({ location: { type: Object } })
.