0

I have a collection of words, the scheme is as follows:

var wordsSchema = new Schema({

    name         : { type : String  , trim : true , required : true , unique : true , index: true},
    definition   : { type : String  , trim : true , required : true }

});

when I try to save new word with empty name or definition into collection required: true works end return error,but when I try to update collection and set empty name or definition value required:true doesn't works and updated word with empty fields saves into collection I want to prevent saving empty words into collection. How can I achieve this with a shortest way, My Update code looks like this:

words.update({ _id : word._id }, { $set : {

            name       : word.name,
            definition : word.definition
        } 

    } , function(err,data) {

        if(err) {
            res.status(1033).send("There was error while changing word");
        } else {
            res.send('Word has successfully changed');
        }

    });

1 Answer 1

3

required:true is not something maintained at the database level, but rather mongoose itself handles that for you. when you do an update operation, mongoose doesn't run your validators (required:true is a type of validator).

There is a change coming up in mongoose 4 where validators get run on updates. For now, your options are

  • manually check if there's nothing there (enforced by your application)
  • do a find on the document, then edit the field and do doc.save which will run validators (enforced by mongoose)
  • add a document with an empty value for 'word'. because you have a unique index on that field, mongodb will not allow you to insert another document without a value for that field (enforced by mongodb)

I would recommend that last option.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.