How to create a mongoose schema dynamically? - node.js

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.

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);

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);

Related

Able to add to database in MongoDB but not mongoose

I am learning about Mongoose. I am working along this tutorial and running into a stumbling block with adding entries to my database, run through Heroku MongoDB. I am able to add to the existing collection "test1" when I load the app 'trywithmongodb' but I in my Heroku mLab console I do not see anything added to any collections when I access the page "trywithmongoose". Help? Here is the relevant code for in index.js:
var express = require('express');
var mongoose = require("mongoose");
var mongo = require('mongodb').MongoClient;
app.get("/trywithmongodb", function(request,response){
response.send("Looking at the /trywithmongodb page");
var configDB = require('./config/database.js');
//add to the database
mongo.connect(configDB.url , function(err, db) {
var shorturl = db.collection("test1");
var date = new Date();
var newsitejson={original_url: "accessed at", site_number: date.getHours()+":"+date.getMinutes()}
shorturl.insert(newsitejson)
db.close()
})
});
app.get('/trywithmongoose', function (request, response) {
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
// grab the user model
var User = require('./app/models/user');
// create a new user
var newUser = User({
name: 'Peter ',
username: 'peter45',
password: 'willbehashed',
admin: true
});
// save the user
newUser.save(function(err) {
if (err) throw err;
console.log('User created!');
});
response.send("You are looking at /trywithmongoose");
});
And here's the full file user.js for the schema:
// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create a schema
var userSchema = new Schema({
name: String,
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
admin: Boolean
});
// the schema is useless so far
// we need to create a model using it
var User = mongoose.model('User', userSchema);
// make this available to our users in our Node applications
module.exports = User;

Schema has not been registered error on population

When I'm trying to populate , this error is coming:
" MissingSchemaError: Schema hasn't been registered for model "
My models:
/models/course.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = require('./user')
var courseSchema = Schema({
courseName:String,
price:Number,
type:String,
_offeredBy:{type:Schema.Types.ObjectId,ref:User}
});
module.exports = mongoose.model("Course",courseSchem
models/user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');
var findOrCreate = require('mongoose-findorcreate')
var Course = require('./course')
var userSchema = Schema({
email:{type:String},
password:{type:String},
courseOffered:[{type:Schema.Types.ObjectId,ref:Course}]
});
module.exports = mongoose.model('User',userSchema);
routes/index.js
var Course = require('../models/course');
var User = require('../models/user');
var express = require('express');
var router = express.Router();
router.get('/user/profile',isLoggedIn,function(req,res,next){
res.render('user/profile',{csrfToken:req.csrfToken(),message:""})
});
router.post('/user/profile',isLoggedIn,function(req,res,next){
var courseInfo = req.body;
var newCourse = new Course();
newCourse.courseName = courseInfo.coursename;
newCourse.price = courseInfo.price;
newCourse.type = courseInfo.type;
newCourse._offeredBy = req.user;
newCourse.save(function(err,result){
if(err){
res.redirect('/user/profile');
}
});
Course
.findOne({courseName:courseInfo.coursename})
.populate('_offeredBy')
.exec(function(err,course){
if(err){
res.redirect('/user/profile');
}
});
});
Course is getting saved in the database, but the error is coming due to pouplating. I'm not writing the app.js, mongodb connections are made in app.js file.
Your models are trying to load another model which itself then tries to load the other model.
In your schemas you should set the refs as strings like this:
var courseSchema = Schema({
courseName: String,
price: Number,
type: String,
_offeredBy: { type:Schema.Types.ObjectId, ref: 'User' }
});
var userSchema = Schema({
email: String,
password: String,
courseOffered: [{ type: Schema.Types.ObjectId, ref: 'Course' }]
});
You can then remove the lines to require the other model within each model file. They are both loaded in 'routes/index.js' before being used.
Note: newCouse.save() is asynchronous so you should do you Course.findOne().populate() inside the 'save' callback.

can't insert data using mongoose

i am new in mean stack i completed update,delete,and get data but can't insert data in mongoose can anyone help me please.thanks in advance below is my code.
var express = require('express');
var mongojs = require('mongojs');
var db = require('mongoose');
var bodyParser = require('body-parser');
var app = express();
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
db.connect('mongodb://localhost/contactlist');
var db1 = db.connection;
db1.on('error', err);
db1.once('open',startserver);
function err(){
console.log('connection error:');
}
function startserver(){
console.log('start');
app.listen(3000);
}
var contactdetails1 = new db.Schema({
name:String,
email:String,
password:String,
number:String
});
db1.model('Contactdetails',contactdetails1);
app.post('/contactList',function(req,res){
console.log("Get insert request"+req.body);
//var contactList = new ContactList(req.body);
var contactdetails1 = new db.Schema({
name:req.body.name,
email:req.body.email,
password:'',
number:req.body.number
});
contactdetails1.save(function(err,data) {
if (err) {
response = {
"status":0,
"error":err,
};
}else{
response = {
"status":1,
"data":data,
"message":"User registered successfully"
};
}
console.log(response);
res.json(response);
});
});
when inserting data at that time below error show
Undefined type Test at name
Did you try nesting Schemas? You can only nest using refs or arrays.
at Function.Schema.interpretAsType (/usr/lib/node_modules/mongoose/lib/schema.js:666:11)
at Schema.path (/usr/lib/node_modules/mongoose/lib/schema.js:545:29)
at Schema.add (/usr/lib/node_modules/mongoose/lib/schema.js:429:12)
at new Schema (/usr/lib/node_modules/mongoose/lib/schema.js:100:10)
at /var/www/html/contactlistappmvc/server.js:53:25
var contactdetails1 = new db.Schema({
name:req.body.name,
email:req.body.email,
password:'',
number:req.body.number
});
You should be saving a model, not a schema. What you've done here is pass an object to the schema. Documents are instances of Models, not schemas. A schema is just an object definition.
Instead of what you've done here, why don't you do
var ContactModel = mongoose.model('Contactdetails',contactdetails1);
var contactModel = new ContactModel({
name:req.body.name,
email:req.body.email,
password:'',
number:req.body.number
})
And then do a contactModel.save()

How do I partially update an array inside and object in MongoDB so the new value is added to the array

Given the following schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var favoriteSchema = new Schema({
dishes: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Dish'
}],
postedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
}, {
timestamps: true
});
var Favorites = mongoose.model('Favorite', favoriteSchema);
module.exports = Favorites;
and the following router
var bodyParser = require('body-parser');
var express = require('express');
var mongoose = require('mongoose');
var Favorites = require('../models/favorites');
var Verify = require('./verify');
var favoritesRouter = express.Router();
favoritesRouter.use(bodyParser.json());
favoritesRouter.route('/')
.post(Verify.verifyOrdinaryUser, function(req,res,next){
req.body.postedBy = req.decoded._doc._id;
console.log('nana ' + req.body.postedBy);
Favorites.create(req.body,function(err,fav){
if(err) throw err;
fav.dishes.push(req.body);
fav.save(function(err,fa){
if(err) throw err;
res.json(fa);
})
});
});
module.exports = favoritesRouter;
Every time i do the post requires from postman, I`m attaching the dish ID to the body of the request.
{
"_id": "577a996155d73cf02b0d516f"
}
I could not come up with a solution to insert this ID into the array, instead of re-creating the whole object with only 1 id inside the array. Am i making something wrong, or something else has to be done in order to do the logic i want?
You're going to want to query the database to find the previously saved object, append to the array, mark as modified, then save. It will look something like this:
var bodyParser = require('body-parser');
var express = require('express');
var mongoose = require('mongoose');
var Favorites = require('../models/favorites');
var Verify = require('./verify');
var favoritesRouter = express.Router();
favoritesRouter.use(bodyParser.json());
favoritesRouter.route('/')
.post(Verify.verifyOrdinaryUser, function(req,res,next){
req.body.postedBy = req.decoded._doc._id;
console.log('nana ' + req.body.postedBy);
Favorites.findById(someID, function(err, fav){
if(err) throw err;
fav.dishes.push(req.body);
fav.markModified('dishes')
fav.save(function(err,fa){
if(err) throw err;
res.json(fa);
})
});
});
You'll need to figure out how you're getting the ID in there. You could use a dynamic endpoint:
favoritesRouter.use(bodyParser.json());
favoritesRouter.route('/:id')
.post(Verify.verifyOrdinaryUser, function(req,res,next){
var someID = req.params.id
})
Or you could do a search for who posted it (.find({postedBy: req.decoded._doc._id},... instead of .findById(someID,...), or something else

saving unstructured data in mongoose

I am able to save request the data if I explicitly define in my express model the structure, but I am not able to save record if I do not explicitly define the data structure.
For example I am able to save if I have this in my model
....
module.exports = mongoose.model('Form', new Schema({
name: String,
password: String,
admin: Boolean
}));
...
...
but I am not able to save it if I have it like this
module.exports = mongoose.model('Form', new Schema());
Here is my model
// get an instance of mongoose and mongoose.Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// set up a mongoose model and pass it using module.exports
module.exports = mongoose.model('Form', new Schema());
And here is my Router
apiRouter.post('/forms/createForm', function(req, res) {
var form = new Form(req.body);
form.save(function(err) {
if (err) throw err;
console.log('Form saved successfully');
res.json({ success: true });
});
});
Thanks
Ok I got that working.
There is a strict false option that I can use to define the schemaless structure.
Thats how I did it:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// set up a mongoose model and pass it using module.exports
module.exports = mongoose.model('Form', new Schema({}, { strict: false} ));

Resources