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?
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.