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?
ref: 'Match._id'