I'm making a node app to consume json API and I'd like to separate parts of User
schema into separate files because there are many fields in Profile
and separating files keeps things cleaner:
So basically instead of
const userSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
profile: {
gender: {
type: String,
required: true
},
age: {
type: Number
},
//many more profile fields come here
}
});
I do this:
models/Profile.js
is:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const profileSchema = new Schema({
gender: {
type: String,
required: true
},
age: {
type: Number
}
//the rest of profile fields
});
module.exports = Profile = mongoose.model('profile', profileSchema);
And the models/User.js
is:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Profile = require('./Profile');
const userSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
profile: {type: Schema.Types.ObjectId, ref: 'Profile'},
});
module.exports = mongoose.model('users', userSchema);
The data for User
and Profile
are posted in the same json post.
However when node tries to save the object I get this error:
(node:4176) UnhandledPromiseRejectionWarning: ValidationError: users validation failed: profile: Cast to ObjectID failed for value "{ gender: 'male'...
How can I fix this?
You can define it like this:
/Match.js:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const matchSchema = new Schema({
gender: {
type: String,
required: true
},
age: {
type: Number
}
});
export const mongooseMatch = mongoose.model('match', matchSchema);
/User.js:
import mongooseMatch from './Match.js';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Match = require('./Match');
const userSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
match: {type: Schema.Types.ObjectId, ref: 'Match'},
});
export const matchUser = userSchema.discriminator('matchUser', mongooseMatch);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With