用Mongoose保存无模式logging?
所以我一直在试图用混合模式将CSP报告保存到Mongoose中,并且遇到了各种各样的问题。
如果我尝试使用“无模式”方式保存任何内容,则只保存默认的_v
和_id
字段
ViolationSchema = new Schema({}); Violation = mongoose.model('CSPViolation', ViolationSchema); ... wait for POST ... new Violation( req.body ).save( callback ); // { _id : <some_id>, _v : <some_hash> }
如果在架构中将字段设置为Mixed
,并将.markModified()
添加到字段,则会保存。
ViolationSchema = new Schema({ report : { type : Mixed } }); Violation = mongoose.model('CSPViolation', ViolationSchema); ... wait for POST ... var v = new Violation( { report : req.body } ); v.markModified('report'); v.save( callback ); // report saved under v.report.<actual_report>
我想过使用本地MongoDB样式的collection.insert
,但是看起来模型没有插入方法(也不是模式)。
我想我也可以通过我保存的报告中的每个键,并手动将其标记为已修改,但是我希望避免只存储这样的报告。
任何想法如何我可以用Mongoose盲目保存混合模式types?
看起来这可以通过在模式上设置{ strict : false }
来完成。 这可以确保Mongoose将保存未在原始模式中声明的任何字段。
通常情况下,这不是你在95%的数据上启用的东西,它完全符合我目前所要做的。
例
ViolationSchema = new Schema({ type: Mixed }, { strict : false }); Violation = mongoose.model('CSPViolation', ViolationSchema); ... wait for POST ... new Violation( req.body ).save( callback ); // Saves with full data