gpt4 book ai didi

node.js - Mongoose {严格: throw} doesn't throw error

转载 作者:可可西里 更新时间:2023-11-01 10:02:41 27 4
gpt4 key购买 nike

我试图到处寻找这个问题的答案,但似乎我运气不好。

我有一个非常简单的 Mongoose 模型

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

并且,当我创建架构时,我选择了在添加不在模型中的属性时抛出错误的选项。

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

这就是我试图捕捉错误的方式。当我添加有效属性时,进程会运行并记录创建的文档,但当我添加无效属性时,进程永远不会退出,并且日志永远不会出现在控制台上。

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

我做错了什么?

最佳答案

文档说:

https://mongoosejs.com/docs/guide.html#strict

The strict option, (enabled by default), ensures that values passed to our model constructor that were not specified in our schema do not get saved to the db

The strict option may also be set to "throw" which will cause errors to be produced instead of dropping the bad data.

但这并不代表你认为的意思。

NOTE: Any key/val set on the instance that does not exist in your schema is always ignored, regardless of schema option.

因此,“不良数据”仅包含架构中但格式错误的数据。模式中NOT 的任何额外数据都将被静默删除,从而导致最大程度的脱发并违反 POLA。

关于node.js - Mongoose {严格: throw} doesn't throw error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41419201/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com