使用Mongoose保存无架构记录?

Alb*_*elB 1 mongoose node.js

因此,我一直在尝试使用混合模式将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> }
Run Code Online (Sandbox Code Playgroud)

如果我在架构中设置了一个字段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>
Run Code Online (Sandbox Code Playgroud)

我考虑过使用本机MongoDB风格collection.insert,但它看起来不像模型有插入方法(也不是模式).

我想我也可以查看我正在保存的报告中的每个密钥,并手动将其标记为已修改,但我想避免这样只是为了存储此类报告.

我有什么想法可以使用Mongoose盲目保存混合模式类型?

Alb*_*elB 6

看起来这可以通过设置{ 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
Run Code Online (Sandbox Code Playgroud)