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

时间:2018-10-23 15:11:17

标签: javascript node.js mongodb mongoose mongoose-schema

我有问题。我是node.js和mongoDB的新手(使用猫鼬)。在MySQL中,当我定义了带有必填字段的表时,数据库将拒绝接受不符合模型规则的输入。我注意到,至少在mongoDB中,我的设置方式并非如此。

我在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');

在此,我为required:true以外的所有字段设置了date。然后,我在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;

但是,当我执行插入功能时,即使标记为required的字段留为空白,它也会毫无错误地接受它。在解决如何验证插入到mongoDB集合中的数据方面的任何帮助,我将不胜感激。

我正在使用mongoos版本5.3.6和mongoDB版本4.0.3

谢谢。

修改 感谢所有回答,根据下面的一些评论,我将dataStructure.collection.insertOne()更改为dataStructure.create(),其中似乎包含了验证。

2 个答案:

答案 0 :(得分:1)

您还需要在提交时或提交之前添加验证。如果表单有错误,则实际上是无效的,因此请在提交之前检查它是否无效。

您的代码似乎有些冗长,复杂且令人困惑。.您是否有理由这样做?例如,您正在使用猫鼬模式,但实际上并未使用猫鼬方法提交,这就是为什么没有进行任何验证的原因。insertOne不是猫鼬方法,并且您没有使用模型来保存条目。那将是model.save(data)

您还可以直接保存,而无需再次调用架构,只需声明一个新变量即可。

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));

答案 1 :(得分:0)

我相信您传递的是空字符串,这就是为什么验证程序不会将条目标记为错误的原因。尝试为这些字段传递null并检查行为。