AlbertEngelB
AlbertEngelB

Reputation: 16436

Saving Schema-less Records with Mongoose?

So I've been trying to save CSP reports into Mongoose with a Mixed schema and have ran into a snag of sorts.

If I try to save anything using the "schema-less" way, it only saves the default _v and _id fields

ViolationSchema = new Schema({});
Violation = mongoose.model('CSPViolation', ViolationSchema);

... wait for POST ...

new Violation( req.body ).save( callback );
// { _id : <some_id>, _v : <some_hash> }

If I set a field in the schema to be Mixed and add a .markModified() to the field, it will save.

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>

I thought about using native MongoDB-style collection.insert, however it doesn't look like the model has an insert method (nor the schema for that matter).

I suppose I could also go over each key in the report I'm saving and manually mark it as modified, but I'd like to avoid that just to store a report such as this.

Any ideas how I can blindly save a mixed schema type using Mongoose?

Upvotes: 1

Views: 2903

Answers (1)

AlbertEngelB
AlbertEngelB

Reputation: 16436

It looks like this can be done by setting { strict : false } on the schema. This ensures that Mongoose will save any fields that weren't declared in the original schema.

Normally this isn't something you would enable on 95% of your data, it just fits perfectly with what I'm trying to do currently.

Example

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

Upvotes: 6

Related Questions