Nasiruddin Saiyed
Nasiruddin Saiyed

Reputation: 1466

How to create a mongoose schema dynamically?

I am new in mean and trying to to create a mongoose schema dynamically.

this is my model for deo:

var mongoose=require('mongoose');
Schema=mongoose.Schema;
var deoSchema=new Schema({
     name: String
});
module.exports = mongoose.model('deo',deoSchema);

this is how i save it :

var deo = function () { };
deo.prototype.create = function (req, res) {
    var deo=new Deo(req.body);
    deo.save(function(err,doc){
        if(err){
            console.log('error occured..'+err);
        }
        else{
            res.json(doc);
        }
    });
}

now i want to try to store other fileds to store it in mongodb and tried to use {$upsert=true} while saving and edited my model as below

var mongoose=require('mongoose');
Schema=mongoose.Schema;
var deoSchema=new Schema({
     name: String,
     type:[Schema.Types.Mixed]
});
module.exports = mongoose.model('deo',deoSchema);

but not able to save it and what should i do to save dynamically those fields which are not in schema of mongodb.

Upvotes: 1

Views: 3308

Answers (2)

Sadaf Sid
Sadaf Sid

Reputation: 1570

in my case i just edited a bit.

const mongoose=require('mongoose');
Schema=mongoose.Schema;
const deaoSchema=new Schema(
    { type : Schema.Types.Mixed}, 
    {strict: false});
module.exports = mongoose.model('deao',deaoSchema);

Upvotes: 0

Nasiruddin Saiyed
Nasiruddin Saiyed

Reputation: 1466

i Just tried this and edited my schema as below and just passed name as required in form

var mongoose=require('mongoose');
Schema=mongoose.Schema;
var deaoSchema=new Schema(Schema.Types.Mixed, {strict: false});
module.exports = mongoose.model('deao',deaoSchema);

Upvotes: 3

Related Questions