【问题标题】:How to validate db.collections.insertOne inputs on mongoose and node.js如何在 mongoose 和 node.js 上验证 db.collections.insertOne 输入
【发布时间】:2018-10-24 23:33:29
【问题描述】:

我有问题。我是 node.js 和 mongoDB 的新手(使用 mongoose)。在 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');

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

谢谢。

编辑 感谢所有回复的人,根据下面的一些 cmets,我将 dataStructure.collection.insertOne() 更改为 dataStructure.create(),这似乎包括验证。

【问题讨论】:

  • 显示您正在收集数据以获得更完整答案的表格

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


【解决方案1】:

您需要在提交时或在提交之前添加验证。当表单有错误时,它实际上是无效的,所以在提交之前检查它是否无效..

Tbh 你的代码看起来有点冗长、复杂和混乱.. 你这样做有什么原因吗?例如,您使用的是 mongoose 模式,但实际上并未使用 mongoose 方法提交,这就是为什么您没有进行任何验证的原因。 insertOne 不是 mongoose 方法,并且您没有使用模型来保存条目。应该是 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));

【讨论】:

  • 感谢您的回复。我在提交时为表单添加了一些 JS 验证。但是,我的问题是我的插入代码似乎忽略了模型中指定的约束。它也忽略了default:Date.now。所以我想知道是否可以让它在验证之上使用这些约束。我不知道这是否可能,因为我习惯了 MySQL,其中数据库拒绝不符合其模型的插入。如果这是不可能的,那么我为我缺乏 mongoDB 和 mongoose 的知识而道歉。
  • 好吧,你的回电是什么?当您说 Date.now 被忽略时,因为 Date.now 不是函数调用.. Date.now();是被调用的函数还是 new Date()
  • Tbh 你的代码看起来有点冗长、复杂和混乱。你这样做有什么理由吗?例如,您使用的是 mongoose 模式,但实际上并未使用 mongoose 方法提交,这就是为什么您没有进行任何验证的原因。 insertOne 不是 mongoose 方法,并且您没有使用模型来保存条目。它将是 model.save(data)
【解决方案2】:

我相信您传递的是空字符串,这就是验证器没有将条目标记为错误的原因。尝试为字段传递 null 并检查行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-03
    • 2023-01-13
    • 2016-04-10
    • 2012-01-13
    • 2022-01-01
    • 2017-03-24
    • 1970-01-01
    相关资源
    最近更新 更多