Mongoose 不强制执行模式中指定的类型
Mongoose not enforcing type specified in schema
我创建了一个 Mongoose "Costs" 对象,该对象已成功保存到 Mongo 集合中。在成本对象的 Mongoose 架构中,我为每一列指定了类型:
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var crypto = require('crypto');
var CostsSchema = new Schema({
property_hash:String,
month: Number,
year: Number,
spend: Number,
updated_by: String,
channel: String,
source: String,
updated: Date
});
mongoose.model('Costs', CostsSchema);
但是当我调用 Costs.collection.insert() 传递所有属性都设置为字符串的对象数组时,它们会毫无错误地保存到 Mongo。
成功保存的无效对象示例:
{ channel: "websites",
month: "I should be an integer",
property_hash: "1234566",
source: "trade",
spend: "I am an invalid integer",
updated: "I am an invalid date",
updated_by: "fred",
year: "Invalid year" }
如果您查看 docs,您会发现这不是在 Mongoose 中实现的方法,而是在 MongoDB 驱动程序中实现的,因此不会进行验证at all - 文档直接保存到 Mongo.
根据您的需要,您最好使用#insertMany方法。
我创建了一个 Mongoose "Costs" 对象,该对象已成功保存到 Mongo 集合中。在成本对象的 Mongoose 架构中,我为每一列指定了类型:
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var crypto = require('crypto');
var CostsSchema = new Schema({
property_hash:String,
month: Number,
year: Number,
spend: Number,
updated_by: String,
channel: String,
source: String,
updated: Date
});
mongoose.model('Costs', CostsSchema);
但是当我调用 Costs.collection.insert() 传递所有属性都设置为字符串的对象数组时,它们会毫无错误地保存到 Mongo。
成功保存的无效对象示例:
{ channel: "websites",
month: "I should be an integer",
property_hash: "1234566",
source: "trade",
spend: "I am an invalid integer",
updated: "I am an invalid date",
updated_by: "fred",
year: "Invalid year" }
如果您查看 docs,您会发现这不是在 Mongoose 中实现的方法,而是在 MongoDB 驱动程序中实现的,因此不会进行验证at all - 文档直接保存到 Mongo.
根据您的需要,您最好使用#insertMany方法。