user2316341
user2316341

Reputation: 375

Mongoose - flexible field

I am new to NOSQL and MongoDB, I am building an app with NodeJS and Mongoose, and I am building a mongoose schema for a new collection.

The documents of this collection will have some standard fields (id, creation date, user etc...) but then I need to store other stuff, which is a "data" field which will have to contain different data depending on the document. The value will sometimes be simple text and other times it will have lots of key/values pairs.

I am wondering what would be the best solution for this kind of storing needs :

-Create only one "data" field with a String type and then put different types of data into it (text for simple values, stringified objects for more complex data)

-Create in the model all the possible fields that my "more complex data" could have and use only the ones I need in each document

-Something else

What is the best practice for this kind of thing ?

Upvotes: 4

Views: 3222

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 311865

This one:

-Create in the model all the possible fields that my "more complex data" could have and use only the ones I need in each document

Mark the standard fields of the schema as required: true and leave the rest optional. That way you get the flexibility you want without losing the Mongoose benefits of validation, casting, and change detection.

Upvotes: 2

Celestz
Celestz

Reputation: 311

Try to use the Mixed schemaType, I think that's what you are looking for: http://mongoosejs.com/docs/schematypes.html

Upvotes: 4

Related Questions