Able to add to database in MongoDB but not mongoose - node.js

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;

Related

Why am I getting [] in the json response in postman always?

// controllers/users.js
'use strict';
var mongoose = require('mongoose'),
User = mongoose.model('Users');
exports.list_all_users = function(req, res) {
User.find({}, function(err, users) {
if (err)
res.send(err);
res.json(users);
});
};
// exports.list_all_users = function(req, res){
// res.send("display all users");
// };
exports.create_a_user = function(req, res){
res.send("user_created");
};
exports.delete_a_user = function(req, res){
res.send("user_deleted");
};
./routes/users.js
'use strict';
module.exports = function(app) {
var users = require('../controllers/users');
// users Routes
app.route('/users')
.get(users.list_all_users);
}
model/UserModel.js
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
_id:{
type : Number,
auto : true },
name: {
type : String,
required: 'Kindly enter the name '
},
password: {
type: String
},
email:{
type: String,
required: 'Kindly enter the mailId '
},
role:{
type: String,
required : 'Enter a valid role '
},
invitedBy: {
type: Number,
required : 'Valid number'
}
});
module.exports = mongoose.model('Users', UserSchema);
server.js
var express = require('express'),
app = express(),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
User = require('./model/UserModel'), //created model loading here
bodyParser = require('body-parser');
// mongoose instance connection url connection
var dbConfig = require('./db');
mongoose.Promise = global.Promise;
mongoose.connect(dbConfig.config);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var userRoutes = require('./routes/users'); //importing route
userRoutes(app); //register the route
app.listen(port);
console.log('todo list RESTful API server started on: ' + port);
I tried printing 'display as respone' to response and it works, the database connection is successful.
But when I try to get from the db, it prints[] for /users get
I suspect something is wrong with my model
Can anyone point out what went wrong here ?
My collection:
collection : "Users"
{
"_id": 112,
"name": "abcd",
"password": "hash12341234",
"email": "questioner#hotmail.com",
"role": "musician",
"invitedBy": 1
}
In you controllers/user.js, you have tried to created a user model again. Can you try importing as follows,
var mongoose = require('mongoose'),
User = require('../model/UserModel')
In you userModel.js, you need to also place a connection string
var db = mongoose.connect("mongodb://localhost/XXXXX");
var Schema = mongoose.Schema;
You just need to replace a line in controller/user.js
Use:
User = require('../model/UserModel')
instead of:
User = mongoose.model('Users');
Hope this helps.
Actually, the issue is that, the get function is returning the objects in collection created only using the model in Node.
I tried creating the user with the api and tested get users but it works like charm.
I am still puzzled about why it is unable to return the objects from the collection which were created by me manually.

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)

Mongoose doesn't insert in MongoLab

I'm trying to build my first MEAN Stack application and I'm using postman to check my insertion in my DB and I get a message that says "user created!", but after checking the DB in MongoLab. I do not get any document inserted in the collections. here's my code:
Here's my repo in case you need it: https://github.com/pevargasg/joberistyNode
app.js
var express = require('express')
var app = express()
var morgan = require('morgan');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
//My one modules
var User = require('./app/models/user');
var Company = require('./app/models/company');
//Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(morgan('dev'));
//Connection to DB
//mongoose.Promise = global.Promise;
//Feel free to use your own mongoLab link below for testing purposes
mongoose.connect('mongodb://user:password#dsXXXXXX.mlab.com:19768/jobersity',function(err){
if(err){
console.log("Not connection to DB" + err);
throw err;
}
else{
console.log("Connected to DB");
}
});
//Routes
/*app.get('/', function (req, res) {
res.send('Hello World!')
})*/
//Creating Users
app.post('/users',function(req,res){
//res.send('test');
var user = new User();
user.username = req.body.username;
user.password = req.body.password;
user.email = req.body.email;
/*user.firstName = req.body.firstName;
user.lastName = req.body.lastName;
user.major = req.body.major;*/
//Save user
user.save();
res.send('user created!');
});
user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//Table for usersSchema
var UserSchema = new Schema({
username:{type: String, lowercase: true, required: true, unique: true},
password:{type: String, required: true},
email:{type: String, lowercase: true, required: true, unique: true},
/*firstName: {type: String, required: true},
lastName: {type: String, required: true},
major: {type: String, required: true},
jobsApplied:[{
title: String,
description: String,
position: String
}]*/
});
module.exports = mongoose.model('User', UserSchema);
Your code works successfully when I run it.
Two things I did notice:
Your package.json file includes mongojs when it doesn't seem to get used. The mongooose package will pull the mongodb dependency it need when you call npm install.
Your connection string is included in clear text in your repository. Try to get in the habit of importing any sensitive information into your app through a config file.
For example, create a config file, e.g. ./config/db.js:
module.exports = {
'uri' : 'mongodb://user:pwd#host1:port1/dbname'
}
Then import the file into your app:
var dbConfig = require('./config/db.js');
The variable can then be used be used in your code:
mongoose.connect( dbConfig.uri, function(err){ ... } )
Finally, add this file (./config/db.js) to your .gitignore.

1 of 2 Mongoose schema not getting initialized

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

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!' });
});

Resources