Home > Mobile >  Mongoose scheme nested in other scheme ref/default doesn't work
Mongoose scheme nested in other scheme ref/default doesn't work

Time:12-27

I got schema..

....
const translateLanguageSchema = new mongoose.Schema({
 
  order:
  {
    orderBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User', default: '5ebsb5fc538d873da8911ec7' },
  }
....

and when i am using this schema in different schema below (the same file)

polish: translateLanguageSchema,
german: translateLanguageSchema,

Mongoose doesn't save the default userID in mongodb database.

However if i do it like that

polish: 
 order:
  {
    orderBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User', default: '5ebsb5fc538d873da8911ec7' },
  }

It works perfectly.

Is there a way to fix it? I just want to avoid code repetition..

I tried to remove const.. I know that i can add this to save() but i just want to use the default() instead without adding it to the query.

CodePudding user response:

as far as I know, you can only instantiate one mongoose Schema inside a given 'schema', I my case I've created some simple vanilla js objects, then I added them to my final schema to avoid the DRY principle.

const translateLanguage = {
    order:
    {
        orderBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User', default: '5ebsb5fc538d873da8911ec7' },
    }
};

then:

   YourFinalSchema({
....,
polish: translateLanguage,
german: translateLanguage,
});
  • Related