Dawid Pura
Dawid Pura

Reputation: 1029

How to clone Mongoose schema?

I am working on Mongoose plugin that have to access existing model and create similar schema as previous model and fix some attributes and add some custom properties. How to do such cloning of scheme? I tried but its not working:

var mongoose = require('mongoose');

var mainSchema = new mognoose.schema({'prop' : String});
var anotherSchema = new mongoose.schema(mainSchema);

Of course, its not working at all and I can't find any solution in API doc and source code (as far I can read that code).

Upvotes: 4

Views: 3770

Answers (2)

alreit
alreit

Reputation: 322

For anyone googling, try:

schema.clone();

This creates a full copy of the schema, so you can add more properties, multiple discriminators, etc.

http://mongoosejs.com/docs/api.html#schema_Schema-clone

Upvotes: 11

Yuri Zarubin
Yuri Zarubin

Reputation: 11677

Assign the schema to a regular object first:

var mongoose = require('mongoose');

var schemaObj = {'prop' : String}
var mainSchema = new mongoose.Schema(schemaObj);
var anotherSchema = new mongoose.Schema(schemaObj);

Upvotes: 3

Related Questions