简体   繁体   English

如何在猫鼬和node.js上验证db.collections.insertOne输入

[英]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). 我是node.js和mongoDB的新手(使用猫鼬)。 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. 在MySQL中,当我定义了带有必填字段的表时,数据库将拒绝接受不符合模型规则的输入。 I have noticed that in mongoDB, at least, the way I have set it up, this is not the case. 我已经注意到,至少在mongoDB中,我的设置方式并非如此。

I have defined the following model in blog-schema.js : 我在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 . 在此,我为date以外的所有字段设置了required:true I then implemented this in conn.js : 然后,我在conn.js实现了这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. 但是,当我执行插入功能时,即使标记为required字段留为空白,它也会正确接受。 I would really appreciate any assistance in working out how to validate the data inserted into the mongoDB collection. 在解决如何验证插入到mongoDB集合中的数据方面的任何帮助,我将非常感谢。

I am using mongoos version 5.3.6, and mongoDB version 4.0.3 我正在使用mongoos版本5.3.6和mongoDB版本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. 编辑感谢所有回答,根据下面的一些评论,我将dataStructure.collection.insertOne()更改为dataStructure.create() ,其中似乎包含验证。

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. 例如,您正在使用猫鼬模式,但实际上并未使用猫鼬方法提交,这就是为什么没有进行任何验证的原因。insertOne不是猫鼬方法,并且您没有使用模型来保存条目。 it would be model.save(data) 这将是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. 尝试为字段传递null并检查行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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