Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import one mongoose schema to another?

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?

like image 387
Babr Avatar asked Nov 22 '18 08:11

Babr


1 Answers

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);
like image 178
muellerra Avatar answered Sep 25 '22 23:09

muellerra