Maria Jane
Maria Jane

Reputation: 2403

Mongodb dynamic schema to save any data

We often define a schema like this

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var Account = new Schema({
    username: String,
    password: String
});

module.exports = mongoose.model('account', Account);

And we have to pass in object that matches the schema otherwise nothing worked. But says I want to save something that's dynamic, and I don't even know what are them for example it can be

{'name':'something',birthday:'1980-3-01'}

or just anything else

{'car':'ferrari','color':'red','qty':1}

How do you set the schema then?

Upvotes: 5

Views: 5368

Answers (2)

abdulbari
abdulbari

Reputation: 6242

You can use strict: false option to your existing schema definition by supplying it as a second parameter in Schema constructor:

Example

var AccountSchema = new Schema({
    Name : {type: String},
    Password : {type: String}
}, {strict: false});

module.exports = mongoose.model('Account', AccountSchema);

You can also use Mixed type

var TaskSchema = new Schema({
   Name : {type: String},
   Email : {type: String},
    Tasks : [Schema.Types.Mixed]
}, {strict: false});

module.exports = mongoose.model('Task', TaskSchema);

Upvotes: 2

Matt
Matt

Reputation: 74899

Mongoose has a Mixed schema type that allows a field to be any object.

var Account = new Schema({
    username: String,
    password: String,
    anyobject: Schema.Types.Mixed
});

Upvotes: 2

Related Questions