codejammer
codejammer

Reputation: 469

Save schemas in DB using Mongoose

I am trying to save the schema directly in DB using Mongoose. Here is the code (schema.js) to save in MongoDB :

var mongoose = require('mongoose');
var Mixed = mongoose.Schema.Types.Mixed;
var modelSchema = mongoose.Schema({
schemaname:String,
object : Mixed
})

var Model = mongoose.model('Model',modelSchema);

exports.createModel = function(model){
var model_to_create = new Model(model);
console.log("creating a schema..." + model)
model_to_create.save(function(err,data){
    console.log("Saving a schema...")
    if(err){
        return "model creation failed";
    }else {
        return "model creation success";
    }
});

}

I am creating a schema using the following piece of code :

var schema = require('../schemas/schema');     
var status = schema.createModel({
    "username": String,
    "firstname": String,
    "lastname": String,
    "description": String,
    "education": String
})

For some reason, the schema is not getting saved in the DB. When I print "status" , I get "undefined"

Can anyone help me how I can solve this issue?

Upvotes: 1

Views: 8768

Answers (2)

Félix Brunet
Félix Brunet

Reputation: 2173

to add to the previous answer, to save mongoose data Types, there is a simple way : save them as string. when retreiving the schema data from the database, you simply need to use mongoose.Schema.Types["String"] to get the data Types of string.

I had a similar use case, and I created a simple recursive function to transform Schema data saved in database in Schema Object :

function changeSchemaType(fields) {
    var f;
    for(key of Object.keys(fields)) {
        f = fields[key];
        if(f.type && typeof f.type === 'string') {
            f.type = mongoose.Schema.Types[f.type]
        } else if(Array.isArray(f.type)){
            f.type = [mongoose.Schema.Types[f.type[0]]];
        } else {
            changeSchemaType(f);
        }
    }
}

the function also permit to create array of type simply in passing : ["String"] for type.

by example :

var data = {
    data1 : {type : "Number", required : true},
    data2 : {type : ["String"]}
}
changeSchemaType(data);
var mySchema = new Schema("mySchema", data)

the function does not handle the shorthand syntaxe like field : "Mixed", but it could be adapted to if needed.

Upvotes: 0

robertklep
robertklep

Reputation: 203574

Saving the model is an asynchronous operation, you have to wait until it's callback is called before you can read the results. A common way to do that is to pass a function which will be called when the saving is done:

exports.createModel = function(model, callback) {
  var model_to_create = new Model(model);
  console.log("creating a schema..." + model)
  model_to_create.save(function(err,data){
    callback(err, data); // <-- called when save is ready
  });
};
...
var schema = require('../schemas/schema');     
schema.createModel({
    "username": String,
    "firstname": String,
    "lastname": String,
    "description": String,
    "education": String
}, function(err, data) { // <-- this is the callback you pass
  // here you handle the results of saving the model
});

EDIT: also, your model has only two properties (schemaname and object), but you're passing 5 properties to its constructor. If your intention is to save each one, you need to save them separately:

schema.createModel({
  schemaname : 'username',
  object     : 'String' // (you probably need to stringify your type, you can't save a class to MongoDB)
}, function(err, data) { ... });

If you want/need to wait for all entries to be saved before you continue, you can use async as a way of coordinating multiple asynchronous operations.

Upvotes: 4

Related Questions