Git Product home page Git Product logo

Comments (10)

Zig1375 avatar Zig1375 commented on September 26, 2024

I provided it above. On my side that code does not work correctly

from mongoose.

Zig1375 avatar Zig1375 commented on September 26, 2024

repro.js.zip

import mongoose from 'mongoose';

await mongoose.connect('mongodb://localhost:27017/test?directConnection=true');

const PhotoValidator = {
  validator: function(photo) {
    console.log('Validation');
    return photo.path.startsWith('photos/car/');
  },
  message: 'invalid'
};


const PhotoSchema = new mongoose.Schema({
  path: {
    type: String,
    required: true,
    trim: true,
  }
});

const CarSchema = new mongoose.Schema({
  photo: {
    type: PhotoSchema,
    required: true,
    validate: PhotoValidator
  }
});

const CarModel = mongoose.model('CarModel', CarSchema);


await CarModel.deleteMany({});
const car = new CarModel({ photo: { path: 'photos/car/bla.jpg' } });
await car.save();
console.log('Created');


car.set('photo.path', 'bla/bla/bla');
// car.photo.path = 'bla/bla/bla';
// const photo = car.get('photo'); photo.set('path', 'bla/bla/bla');

await car.save();
console.log('Saved');


// One more
console.log('---------------------------------');

const car2 = new CarModel({ photo: { path: 'bla/bla' } });

try {
  await car.save();
  console.log('Created');
} catch (error) {
  console.log('Validation error occurred');
}

Result:

$ node repro.js
Validation
Created
Saved
---------------------------------
Validation
Validation error occurred

from mongoose.

Zig1375 avatar Zig1375 commented on September 26, 2024

So, as you can see, in the first case, the creation of a new 'car' occurs without any errors because the path is valid. However, when I attempt to change the path in an existing 'car' to an incorrect one and save it, it also gets saved without any errors...

In the second case, I create a 'car' with an incorrect path, and it doesn't save due to a validation error. The same error is expected to occur in the first case when updating.

from mongoose.

Zig1375 avatar Zig1375 commented on September 26, 2024

it happens not only with set. I commented out other cases it happens as well:

car.photo.path = 'bla/bla/bla';

also does not work.

Any of these ways cannot work

// car.set('photo.path', 'bla/bla/bla');
car.photo.path = 'bla/bla/bla';
// const photo = car.get('photo'); photo.set('path', 'bla/bla/bla');

car.save();

from mongoose.

Zig1375 avatar Zig1375 commented on September 26, 2024

but if I add the validate method inside the subdocument (directly to the path field) it works as expected.
The problem is only when validation is on an entire subdocument field...

from mongoose.

IslandRhythms avatar IslandRhythms commented on September 26, 2024
const mongoose = require('mongoose');

const PhotoValidator = {
  validator: function(photo) {
    console.log('Validation');
    return photo.path.startsWith('photos/car/');
  },
  message: 'invalid'
};


const PhotoSchema = new mongoose.Schema({
  path: {
    type: String,
    required: true,
    trim: true,
  }
});

const CarSchema = new mongoose.Schema({
  photo: {
    type: PhotoSchema,
    required: true,
    validate: PhotoValidator
  }
});

const CarModel = mongoose.model('CarModel', CarSchema);

run().then(() => process.exit(0)).catch(e => {
  console.log(e);
  process.exit(-1);
})

async function run() {
  await mongoose.connect('mongodb://localhost:27017');
  await mongoose.connection.dropDatabase();
  
  
  
  await CarModel.deleteMany({});
  const car = new CarModel({ photo: { path: 'photos/car/bla.jpg' } });
  await car.save();
  console.log('Created');
  
  
  car.set('photo.path', 'bla/bla/bla');
  // car.photo.path = 'bla/bla/bla';
  // const photo = car.get('photo'); photo.set('path', 'bla/bla/bla');
  
  await car.save();
  console.log('Saved, should not have saved');
  
  
  // One more
  console.log('---------------------------------');
  
  const car2 = new CarModel({ photo: { path: 'bla/bla' } });
  
  try {
    await car.save();
    console.log('Created');
  } catch (error) {
    console.log('Validation error occurred');
  }
}

from mongoose.

vkarpov15 avatar vkarpov15 commented on September 26, 2024

This is expected behavior. When saving an existing document, Mongoose only runs validation on paths that have been changed. That means we don't run validation on subdocument paths if the subdocument wasn't directly modified. So if you were to do car.photo = { path: '/bla/bla' } or car.set('photo.path', '/bla/bla'); car.markModified('photo'); the validator would run, but if you modify photo.path directly then Mongoose won't re-run photo validation.

In general, we recommend putting validators on the paths they're validating. So PhotoValidator belongs on the path property, not photo. Does that make sense?

from mongoose.

Zig1375 avatar Zig1375 commented on September 26, 2024

is there a way to run "force" validation? to validate all fields?

from mongoose.

vkarpov15 avatar vkarpov15 commented on September 26, 2024

Yes, but not as elegant as we would like. You need to markModified() every path you want to validate, like car.markModified('photo'). So to validate all paths, you can just markModified() every path in the schema as follows:

car.schema.eachPath(path => car.markModified(path));

We will add a validateAllPaths option in our next minor release that will run validation on every path, not just modified paths.

from mongoose.

Zig1375 avatar Zig1375 commented on September 26, 2024

thank you!

from mongoose.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.