本文介绍了猫鼬{strict:throw}不会抛出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我试图在所有地方找到该问题的答案,但似乎我很不走运.

I tried to find the answer to this question everywhere, but it seems I'm out of luck.

我有一个非常简单的猫鼬模型

I have a very simple mongoose model

var userObject = {
    profile: {
        username: {
            type: String,
            required: true,
            lowercase: true
        },
        firstname: {
            type: String,
            required: true
        },
        lastname: {
            type: String,
            required: true
        },
        img: {
            type: String,
            required: true,
            match: /^(https?:\/\/)/i
        },
        email: {
            type: String,
            match: /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/,
            required: true
        },
        singupdate: {
            type: Date,
            default: Date.now
        }
    }
};

而且,当我创建架构时,我选择了在不添加模型中的属性时引发错误的选项.

And, when I create the schema I choose the option to throw an error when I add properties not in the model.

new mongoose.Schema(userObject, { strict: "throw" });

这是我尝试捕获错误的方法.当我添加有效属性时,该过程将运行,并且会接收创建的文档,但是当我添加无效属性时,该过程将永远不会退出,并且日志也永远不会出现在控制台上.

This is how I tried to catch the error. When I add valid properties the process runs and I recibe the docs created, but when I add invalid properties, the process never exits, and the logs never appear on the console.

try {
    User.create(users, function(err, docs) {
        console.log("err: " + err);
        console.log("docs: " + docs);
    });
} catch (e) {
    console.log(e.message);
}

我在做什么错了?

推荐答案

如果添加不属于模型的属性,请从猫鼬文档:

If you add properties that are not part of the model, from mongoose doc :

即使使用strict:throw,它也可以像这样工作,因此您不必担心模型中未引用的其他字段.

It is working like this even with strict:throw, so you don't have to worry about additional fields not referenced in the model.

关于未触发的异常,Aaron Heckmann在这篇文章关于未在save中使用strict : throw触发的异常:

Concerning the exception not triggered, Aaron Heckmann talks about this in this post regarding that an exception that is not triggered on a save with strict : throw :

由于其他字段不是模型的一部分,因此它们不会触发那些验证,因此不会触发异常(当然这些字段不会保存在数据库中)

As the additional fields are not part of the model, they don't trigger those validation so no exception is triggered (and of course those fields are not saved in the database)

仅当您属于模型的字段未通过此验证时,才会引发异常

Exceptions will be thrown only if your fields that belong to the model fail this validation

这篇关于猫鼬{strict:throw}不会抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 09:46