简体   繁体   中英

How to validate db.collections.insertOne inputs on mongoose and node.js

I have a problem. I am new to node.js and mongoDB (using mongoose). In MySQL when I have defined a table with required fields the database will refuse to accept input that don't conform to the model's rules. I have noticed that in mongoDB, at least, the way I have set it up, this is not the case.

I have defined the following model in blog-schema.js :

const mongoose = require('mongoose');

var Schema = mongoose.Schema;

var userSchema = mongoose.Schema({
        title: {
            type:String,
            required: true,
        },
        author: {
            type: String,
            required: true,
        },
        category: {
            type: String,
            required: true,
        },
        text: {
            type: String,
            required: true,
        },
        date: {
            type: Date,
            default: Date.now,
        },
    })

module.exports = mongoose.model('BlogPost', userSchema, 'blog');

In this, I set required:true for all fields apart from date . I then implemented this in conn.js :

const mongoose = require('mongoose')
, BlogPost = require('./schemata/blog-schema')
, db_config = require('./config')
, uri = 'mongodb://' + db_config.user + ":" + db_config.password + "@" + db_config.host + db_config.database;

 DataFunctions = function (){

    mongoose.connect(uri, db_config.opts);

    mongoose.Promise = global.Promise;

    this.connections = {};
    this.schemas = {};

    this.schemas.BlogPost = BlogPost;

    this.connections.db = mongoose.connection;
};

DataFunctions.prototype.insert = function(data = {}, callback = null) {
    var schema = this.schemas.BlogPost;

    this.connections.db.on('error', console.error.bind(console, 'connection error'));
    this.connections.db.once('open', function(dataStructure = schema) {
        this.items = data;


        if (callback != null) {
            dataStructure.collection.insertOne(this.items, callback);
            mongoose.connection.close();
        }
        else {
            dataStructure.collection.insertOne(this.items, function(err, docs)     {
                if (err) throw err;
            });
            mongoose.connection.close();
        }

    });

    mongoose.connection.close();
    }

    DataFunctions.prototype.retrieve = function(params = {}, columns = '', callback = null) {
    var schema = this.schemas.BlogPost;

    this.connections.db.on('error', console.error.bind(console, 'connection error'));
    this.connections.db.once('open', function(dataStructure = schema) {

        if (callback != null) {
            dataStructure.find(params, columns, callback);
        }
        else {
            dataStructure.find(params, columns, function(err, data) {
                if (err) throw err;
            });

        }
    });


}


module.exports = DataFunctions;

However, when I execute the insert function, it accepts it without error even when fields marked required are left blank. I would really appreciate any assistance in working out how to validate the data inserted into the mongoDB collection.

I am using mongoos version 5.3.6, and mongoDB version 4.0.3

Thank you.

Edit Thanks to everyone who replied, based on some of the comments below I changed dataStructure.collection.insertOne() to dataStructure.create() , which appears to include validation.

You need to add verification on submit as well or before submit. When the form has errors it is actually invalid so check if it is invalid before submitting..

Tbh you code seems a little verbose, complicated and confusin.. is there are reason you are doing it like this? For example you are using a mongoose schema but not actually submitting with the mongoose methods which is why none of your validations are occuring.. insertOne is not a mongoose method, and you aren't using your model to save the entry. it would be model.save(data)

also you can directly save without having to call the schema again, just declare a new variable.

 const post = new BlogPost(data); post.save().then(console.log).catch(console.log); //also mongoose.connect already returns a promise mongoose .connect( dbUrl, { useNewUrlParser: true } ) .then(() => console.log("Connected")) .catch(error => console.log("Failed " + error)); 

I believe you are passing empty string and that's why the validators are not flagging the entries as erroneous. Try passing null for the fields and check the behavaior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM