Skip to content

required validator on single nested subdoc not working after Schema#clone() #8819

Closed
@Vatish12

Description

@Vatish12

Hi, I want to request a feature if it's not available that is a developer should be able to write custom validators for custom nested object that is not a schema.

I am creating a schema like following:


const mediaSkeleton = {
    url: { type: String, required: true },
    thumbUrl: { type: String, required: true },
    mediaType: { type: Number, min: 0, max: 1, required: true },
    aspectRatio: { type: Number, required: true }
}

function requiredObj(x) { 
       console.log(`requiredObj  called for ${x}!`)
       return x != undefined && x != null 
}

const mySchema = new Schema({
       ....
       text: String,
       banner: { type: mediaSkeleton, validate: requiredObj }
       ....
})

I am calling save method on model like following:

const model = mongoose.model("MySchema", mySchema)

await new FaceOffModel(
      { text: "Testing requiredObj validator" }
).save()

requiredObj function doesn't call at all. Please help me to fix it.

Activity

vkarpov15

vkarpov15 commented on Apr 21, 2020

@vkarpov15
Collaborator
const mySchema = new Schema({
       ....
       text: String,
       banner: { type: new Schema(mediaSkeleton), validate: requiredObj } // <-- see `new Schema()` here
       ....
})

This is an unfortunate rough patch in Mongoose's API, we will fix this with #7181

added
helpThis issue can likely be resolved in GitHub issues. No bug fixes, features, or docs necessary
on Apr 21, 2020
Jule-

Jule- commented on May 29, 2020

@Jule-

@vkarpov15 are you sure it works?

I am trying to achieve something like that and I have issues triggering the validation on save on my nested schema pathes.

For me this code is not triggering required validator on path author nor my custom validator function

const authorSchema = new mongoose.Schema({
  name: String,
  pseudonym: String
});

const bookSchema = new mongoose.Schema({
  author: {
    type: authorSchema,
    required: true,
    validate: {
      validator: a => (a.name && a.name.length > 0) || (a.pseudonym && a.pseudonym.length > 0)
    }
  }
});

const Book = mongoose.model('Book', bookSchema);



const book = new Book({});
await book.save(); // return Book instance WITHOUT throwing validation error.

But calling validate on it will throw validation error

await book.validate(); // thow validation error

Did I missed something or is there a workaround to achieve what I want?

added this to the 5.9.18 milestone on Jun 4, 2020
added
has repro scriptThere is a repro script, the Mongoose devs need to confirm that it reproduces the issue
and removed
helpThis issue can likely be resolved in GitHub issues. No bug fixes, features, or docs necessary
on Jun 4, 2020
vkarpov15

vkarpov15 commented on Jun 4, 2020

@vkarpov15
Collaborator

@Jule- the below script throws a "Path author is required" error, as expected.

'use strict';

const mongoose = require('mongoose');

mongoose.set('useFindAndModify', false);

const { Schema } = mongoose;

run().catch(err => console.log(err));

async function run() {
  await mongoose.connect('mongodb://localhost:27017/test', {
    useNewUrlParser: true,
    useUnifiedTopology: true
  });

  await mongoose.connection.dropDatabase();

  const authorSchema = new mongoose.Schema({
    name: String,
    pseudonym: String
  });

  const bookSchema = new mongoose.Schema({
    author: {
      type: authorSchema,
      required: true,
      validate: {
        validator: a => (a.name && a.name.length > 0) || (a.pseudonym && a.pseudonym.length > 0)
      }
    }
  });
  const Book = mongoose.model('Book', bookSchema);

  const book = new Book({});
  await book.save(); // return Book instance WITHOUT throwing validation error. 
  console.log('Done');
}

Can you please clarify what version of Mongoose you're using, and modify the above script to demonstrate your issue?

removed this from the 5.9.18 milestone on Jun 4, 2020
added
can't reproduceMongoose devs have been unable to reproduce this issue. Close after 14 days of inactivity.
and removed
has repro scriptThere is a repro script, the Mongoose devs need to confirm that it reproduces the issue
on Jun 4, 2020
Jule-

Jule- commented on Jun 10, 2020

@Jule-

@vkarpov15 sorry for the delay, I am back!

Thank you, you helped me spotting what is messing things up! 👍
I have set this in my connection code, before creating my Model, of course.

mongoose.set('cloneSchemas', true);

From my point of vue it is a bug, can you confirm that? Or help me understand what can I do to achieve what I want?

Thank you again! 🙂

Jule-

Jule- commented on Jun 10, 2020

@Jule-

And I am using Mongoose version 5.8.9

Jule-

Jule- commented on Jun 11, 2020

@Jule-

Just in order to be clear, the full repro script is:

'use strict';

const mongoose = require('mongoose');

mongoose.set('cloneSchemas', true);
mongoose.set('useFindAndModify', false);

const { Schema } = mongoose;

run().catch(err => console.log(err));

async function run() {
  await mongoose.connect('mongodb://localhost:27017/test', {
    useNewUrlParser: true,
    useUnifiedTopology: true
  });

  await mongoose.connection.dropDatabase();

  const authorSchema = new mongoose.Schema({
    name: String,
    pseudonym: String
  });

  const bookSchema = new mongoose.Schema({
    author: {
      type: authorSchema,
      required: true,
      validate: {
        validator: a => (a.name && a.name.length > 0) || (a.pseudonym && a.pseudonym.length > 0)
      }
    }
  });
  const Book = mongoose.model('Book', bookSchema);

  const book = new Book({});
  await book.save(); // return Book instance WITHOUT throwing validation error.
  console.log('Done');
}

9 remaining items

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    confirmed-bugWe've confirmed this is a bug in Mongoose and will fix it.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @vkarpov15@Jule-@Vatish12

        Issue actions

          `required` validator on single nested subdoc not working after `Schema#clone()` · Issue #8819 · Automattic/mongoose