question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

The required attribute does not work properly on subdocuments

See original GitHub issue

I have a schema containing a property that is an array of another schema (a subdocument), which I would like to be required. I’ve tried to set the required attribute to true for the property, but it does not work as I would like to.

I think it’s best that I show you an example test code:

var should = require('should');
var mongoose = require('mongoose');

// My subdocument schema simplified...
var ThingSchema = new mongoose.Schema({
    name: String
});

// My main document schema...
var CollectionSchema = new mongoose.Schema({
    name: String,
    things: { type: [ThingSchema], required: true } // I don't want this property to be able to be empty...
});

var Collection = mongoose.model('Collection', CollectionSchema);

describe('Saving a Collection', function () {
    var db;

    before(function (done) {
        db = mongoose.connect("localhost", "mongotests");
        done();
    });

    it('fails when it has no things', function (done) {
        var collection = new Collection({
            name: "A collection"
            // I do not set the things property here...
        });
        collection.save(function (err) {
            should.exist(err); // This does not work, but I think it should...
            done();
        });
    });

    it('fails when it has NULL things', function (done) {
        var collection = new Collection({
            name: "A collection",
            things: null
        });

        collection.save(function (err) {
            should.exist(err); // This does work
            done();
        });
    });

    after(function (done) {
        mongoose.disconnect(done);
    });
});

I’ve also tried to set the default property to null for things in the example above, but that does not help either…

Issue Analytics

  • State:closed
  • Created 11 years ago
  • Comments:5

github_iconTop GitHub Comments

2reactions
joakimbengcommented, Sep 21, 2012

I’ve already tried that as well, like this:

var should = require('should');
var mongoose = require('mongoose');

// My subdocument schema simplified...
var ThingSchema = new mongoose.Schema({
    name: String
});

// My main document schema...
var CollectionSchema = new mongoose.Schema({
    name: String,
    things: { type: [ThingSchema], validate: [function (value) { return value.length > 0; }, "Rows missing!"] } // I don't want this property to be able to be empty...
});

var Collection = mongoose.model('Collection', CollectionSchema);

describe('Saving a Collection', function () {
    var db;

    before(function (done) {
        db = mongoose.connect("localhost", "mongotests");
        done();
    });

    it('fails when it has no things', function (done) {
        var collection = new Collection({
            name: "A collection"
            // I do not set the things property here...
        });
        collection.save(function (err) {
            should.exist(err); // This does not work, but I think it should...
            done();
        });
    });

    after(function (done) {
        mongoose.disconnect(done);
    });
});

But the validator function isn’t even executed…

0reactions
Malusiacommented, May 22, 2014

Hello, I have a similar problem.

I have a sub document I cannot modify, because it’s a schema from a global package. In this case a few properties of the child schema are required. I have created a schematic reenactment of my case. It should be noted that the interleaving is lower than on the next level. I have installed Mongoose 3.8.9.

This is the definition of an external source.

var mongoose = require('mongoose');

// comes from a package I cannot edit
var childSchema = new mongoose.Schema({
    name: String,
    age: Number,
    lastMod: Date
});

// this works, but i can not us it
//childSchema.path('name').required(true);

This is my schema.

var mongoose = require('mongoose');

// my schema
var parentSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    age: Number,
    child: [childSchema]
});

// does not work.
parentSchema.path('child').schema.path('name').required(true);

// my model
var Parent = mongoose.model('Parent', parentSchema);

// does not work.
Parent.schema.path('child').schema.path('name').required(true);

This is my test.

var should = require('should');
var mongoose = require('mongoose');

describe('Saving the parent', function () {

    before(function () {
        mongoose.connect('mongodb://localhost/parent-child-test', {db: {safe: true}});
    });

    after(function (done) {
        mongoose.disconnect(done);
    });

    beforeEach(function (done) {
        Parent.remove({}, function (err) {
            if (err) {
                return done(err);
            }

            done();
        });
    });

    it('should trigger the required validation', function (done) {
        var entity = new Parent({
            name: 'Max',
            child: [{age: 12}] // no name set in the sub doc, but no error occurs
        });

        entity.save(function (err) {
            err.should.instanceof(Error);
            done();
        });

    });
});
Read more comments on GitHub >

github_iconTop Results From Across the Web

Mongoose subdocument validation based on required
I have an adress schema and models who using this schema (code below). In one case it is required and in other case...
Read more >
Python sdk add new attribute to existing [RESOLVED]
I would like to be able to add some attribute on an existing document edit an existing attribute The values required on the...
Read more >
Mongoose v6.8.1: SubDocuments
Subdocuments are documents embedded in other documents. In Mongoose, this means you can nest schemas in other schemas. Mongoose has two distinct notions...
Read more >
Mongoose 101: An Introduction to the Basics, Subdocuments ...
Mongoose is a library that makes MongoDB easier to use. It does two things: 1. It gives structure to MongoDB Collections 2.
Read more >
Explanation of the error messages for the W3C Markup Validator
You have used the attribute named above in your document, but the document type you are using does not support that attribute for...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found