1 of 2 Mongoose schema not getting initialized - node.js

I am new to Node and MongoDB. I am using mongoose to create schemas on Mongo. I have created two schemas in 1 models.js file as shown below
var mongoose = require('mongoose');
var postSchema = new mongoose.Schema({
username: String,
text: String,
created_at: {type: Date, default: Date.now}
});
var userSchema = new mongoose.Schema({
username: String,
password: String,
created_at: {type: Date, default: Date.now}
});
//declaring a model which has schema userSchema
mongoose.model("User", userSchema);
mongoose.model("Post", postSchema);
The problem is that my user schema is getting initialized and works fine. But the posts schema is a problem.
This is the error that I get while starting the server:
C:\Users\rohit\Desktop\projects\chirp\module4\start\node_modules\mo
throw new mongoose.Error.MissingSchemaError(name);
^
MissingSchemaError: Schema hasn't been registered for model "Post".
Here is my snippet from the api.js that actually calls post schema to make database queries
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Post = mongoose.model('Post');
...
router.route('/posts')
.get (function(req, res){
Post.find(function(err, data){
if(err){
return res.send(500, err)
}
return res.send(data)
})
})
Here, is the code snippet from my auth.js file that uses the User Schema and it works fine
var LocalStrategy = require('passport-local').Strategy;
var bCrypt = require('bcrypt-nodejs');
var mongoose = require('mongoose');
var User = mongoose.model('User');
var Post = mongoose.model('Post');
module.exports = function(passport){
// Passport needs to be able to serialize and deserialize users to support persistent login sessions
passport.serializeUser(function(user, done) {
console.log('serializing user:',user._id);
return done(null, user._id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user){
if (err){
return done(err, false)
}
if(!user){
return done('User not found', false)
}
return done(user, true);
})
});

You are not loading your models (User and Post) in your models.js.
Add the following lines after var mongoose = require('mongoose');:
var User = require('./models/user.js'); <-- type your user.js model path here
var Post = require('./models/post.js'); <-- type your post.js model path here

Related

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

Can't insert into MongoDB with Mongoose

I'm trying to insert an object in MongoDB with Mongoose, but without success.
In './models/user,js' I have:
var mongoDatabase = require('./db'); //I've connected to localhost here
var database = mongoDatabase.getDb();
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
user: String,
adress: String,
});
userSchema.methods.testmethod = function(){
console.log('test');
}
userSchema.methods.insert = function (obj) { //this works but what is the point to use Mongoose If I do it that way
database.collection("users").insertOne(obj, function(err, res) {
if(err) throw err;
console.log("1 record inserted");
});
}
var User = mongoose.model('User', userSchema);
module.exports = User;
In './controllers/user.js'
var express = require('express');
var router = express.Router();
var User = require('../models/user');
router.post("/", function(request, response) {
var obj = new User({
user: request.body.name,
adress: request.body.adress,
});
obj.testmethod(); //works fine
obj.insert(obj); //throws an error
User.insertOne(obj, function(err, res) { //error: insertOne is not a function
if(err) throw err;
console.log("1 record inserted");
});
});
module.exports = router;
I have tried few more ways to do it, but without result. Can someone help me?
You shouldn't be using whatever mongodb object you're creating in './db' to do this work, mongoose takes care of it for you. Try simplifying down to this:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
user: String,
adress: String,
});
module.exports = mongoose.model('User', userSchema);
Then in your controller code
var express = require('express');
var router = express.Router();
var User = require('../models/user');
router.post("/", function(request, response, next) {
var user = new User({
user: request.body.name,
adress: request.body.adress,
});
user.save(function(err, u) {
if (err) return next(err);
return res.json(u);
});
});
module.exports = router;
Somewhere in your app startup code (often in app.js or similar location) you'll want to call mongoose.connect(<connection url>), normally prior to setting up routes.
Note you can also call insert() explicitly, but it's a static method on the model object, like so:
User.insert({user: 'bob', address: 'somewhere, nh'}, cb)

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;

Mongoose and node js - TypeError: object is not a function

The issue that it doesnt let me use the genre schema
i have 2 schemas user and genre
user schema works fine but the genre schema is undefind
user.js - schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Genre = require('../Models/genre');
// create a schema
var userSchema = new Schema({
name: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
age: String,
gender: String,
genres: [Genre.genreSchema]
});
// 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;
genre.js - schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create a schema
var genreSchema = new Schema({
name: { type: String, required: true, unique: true },
age: String,
gender: String
});
// the schema is useless so far
// we need to create a model using it
var Genre = mongoose.model('Genre', genreSchema);
// make this available to our genres in our Node applications
module.exports = Genre;
genre controller - router --- same as user router controller
var express = require('express');
var bodyParser = require('body-parser');
var Genre = require('../Models/genre');
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router
// middleware to use for all requests
router.use(function(req, res, next) {
// do logging
console.log('Something is happening.');
next(); // make sure we go to the next routes and don't stop here
});
router.route('/genres')
// create a genre
.post(function(req, res) {
console.log(Genre);
**//here is the error when trying to post new genre**
var Genre = new Genre(req.body); // create a new instance of the user model
// save the genre and check for errors
Genre.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Genre created!' });
});
})
// get all the genres
.get(function(req, res) {
Genre.find(function(err, genres) {
if (err)
res.send(err);
res.json(genres);
});
});
module.exports = router;
server.js - the app js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var userRouter = require('./Controllers/user');
var genreRouter = require('./Controllers/genre');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017'); // connect to our datababase
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', userRouter);
app.use('/api', genreRouter);
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('see whats happening on port ' + port);
why the model is undefind only when i post new genre? and for user it works fine?
is it the way to do schema whithin schema? or there is a better way?
i have try to use only the genre model with out the user and it still same error
i hope i am clear enough
thanks for the helpers
You shouldn't be using the same name for the schema and for the new Genre.
try changing it to
var newGenre = new Genre(req.body); // create a new instance of the user model
// save the genre and check for errors
newGre.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Genre created!' });
});

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