Mongoose Validation

Calvin Park·2022년 6월 30일
0

나를 위한 mongoose validation.

const mongoose = require('mongoose');

const taskSchema = new mongoose.Schema({
    name: {
        type: String,
        required: [
            true, "Must provide name."
        ],
        trim: true,
        maxlength:[20, 'name cannot be more than 20 characters.']
    },
    completed: {
        type: Boolean,
        default: false
    },
    quantity: Number
});

//validation
module.exports = mongoose.model('Task', taskSchema);


const testSchema = new Schema({
  number: { type: Number, max: 0 },
  arr: [{ message: { type: String, maxlength: 10 } }]
});

// Update validators won't check this, so you can still `$push` 2 elements
// onto the array, so long as they don't have a `message` that's too long.
testSchema.path('arr').validate(function(v) {
  return v.length < 2;
});

const Test = db.model('Test', testSchema);

let update = { $inc: { number: 1 } };
const opts = { runValidators: true };

// There will never be a validation error here
await Test.updateOne({}, update, opts);

// This will never error either even though the array will have at
// least 2 elements.
update = { $push: [{ message: 'hello' }, { message: 'world' }] };
await Test.updateOne({}, update, opts);

자세한 offical document Link링크텍스트

profile
Personal Velog Note

0개의 댓글