mongoose{strict:throw}不会抛出错误

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

我有一个非常简单的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 } } }; 

而且,当我创build模式时,我select了添加不在模型中的属性时抛出错误的选项。

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

这是我试图抓住错误。 当我添加有效的属性的过程运行,我recibe创build的文档,但是当我添加无效的属性,进程永远不会退出,日志永远不会出现在控制台上。

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

我究竟做错了什么?

如果添加不属于模型的属性,请从mongoose doc :

strict选项(默认启用)确保传递给模型构造函数的值在我们的模式中没有被指定,不会被保存到db

即使在strict:throw情况下也是如此strict:throw ,所以你不必担心模型中没有引用的其他字段。

关于没有触发的例外,Aaron Heckmann在这篇文章中谈到了这个问题,这个例外在save时没有被strict : throw触发strict : throw

这更多的是对mongoose作品的误解。 “严格”选项可以validation试图存储在数据库中的键/值。 模式创build文档实例上的获取者/设置者,这些文档实例被分派到经过validation的doc.{g,s}et()方法。 将临时数据附加到mongoose文档实例不会触发get/set() ,因此不能保证validation,因为这一天没有办法保存到数据库。

由于附加字段不是模型的一部分,因此不会触发这些validation,因此不会触发exception(当然这些字段不会保存在数据库中)

只有当属于模型的字段未通过validation时才会抛出exception