mongodb: Database not showing up in show dbs after data is inserted - node.js

I am following a YouTube tutorial from Jose Annunziato. I created my server.js and did all the required settings and configurations for my database connection. Now when I am posting something from the form to the server: it shows the data is sent to the server successfully but when I go to the mongo console to verify if the data is received and database is created or not. I run db it says test I run show dbs and there I can't see my new Database. I am not sure what the actual problem is because I did everything Jose said in the tutorial.
Server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/blogfall2016');
var PostSchema = mongoose.Schema({
title: {type: String, required: true},
body: String,
tag: {type: String, enum:['POLITICS', 'ECONOMY', 'EDUCATION']},
posted: {type: Date, default: Date.now},
});
var PostModel = mongoose.model('PostModel', PostSchema)
// GET /style.css etc
app.use(express.static(__dirname + '/public'));
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.post("/api/blogpost", CreatePost);
function CreatePost(req, res) {
var post = req.body;
console.log(post);
PostModel.create(post);
res.json(post);
}
app.listen(3000);

If your schema and data you want to insert are matched then it should work.
Try below code. instead of PostModel.create(post);
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/nnnnnn', function (err) {
if (!err) {
console.log('connection successful');
} else {
console.log(err)
}
});
var PostSchema = mongoose.Schema({
title: { type: String, required: true },
body: String,
tag: { type: String, enum: ['POLITICS', 'ECONOMY', 'EDUCATION'] },
posted: { type: Date, default: Date.now },
});
var PostModel = mongoose.model('PostModel', PostSchema)
// GET /style.css etc
app.use(express.static(__dirname + '/public'));
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.post("/api/blogpost", CreatePost);
function CreatePost(req, res) {
var post = req.body;
console.log(post);
// static data
var post = {
title: 'asdfasdf',
body: 'asdfasdfasdfasdf',
tag: 'POLITICS',
posted: new Date()
}
var postModel = new PostModel(post);
postModel.save(function (err, data) {
if (err) {
console.log('Error', err);
} else {
console.log('data inserted');
}
});
res.json(post);
}
app.listen(3000);

Instead of below line
mongoose.connect('mongodb://localhost/blogfall2016');
Try this one to make sure that database created successfully first,
then do your operation
mongoose.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});

Related

MongoDB .find problems NodeJS

When I attempt the code below, I just get an empty return from MongoDB....
let express = require('express');
let mongoose = require('mongoose');
let cors = require('cors');
let bodyParser = require('body-parser');
let testSchema = new mongoose.Schema({
username: String,
name: {
firstname: String,
lastname: String,
},
email: String,
employeeID: String
});
const testModel = mongoose.model('test', testSchema);
mongoose.connect('mongodb://localhost:27017/test', { useUnifiedTopology: true }, function(err, res) {
if (err) console.log(err);
else console.log('Connected to Mongo');
});
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cors());
const port = 5000;
const server = app.listen(port, () => {
console.log('connected to port ' + port);
});
testModel.find({}).exec(function(err, res){
if (!err) {
console.log(res);
}
else {
console.log("Error");
}
})
BUT, when I use this code, it returns the data I'm looking for..... why?! Every other tutorial I have seen operates like the above.
let express = require('express');
let mongoose = require('mongoose');
let cors = require('cors');
let bodyParser = require('body-parser');
let testSchema = new mongoose.Schema({
username: String,
name: {
firstname: String,
lastname: String,
},
email: String,
employeeID: String
});
const testModel = mongoose.model('test', testSchema, 'test');
mongoose.connect('mongodb://localhost:27017/test', { useUnifiedTopology: true }, function(err, res) {
if (err) console.log(err);
else console.log('Connected to Mongo');
});
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cors());
const port = 5000;
const server = app.listen(port, () => {
console.log('connected to port ' + port);
});
testModel.find({}).exec(function(err, res){
if (!err) {
console.log(res);
}
else {
console.log("Error");
}
})
How can I fix this in my code, or is it something within Mongo updates that this is a requirement?
By default, mongoose pluralizes the name of the model when you call mongoose.model() to determine the collection name. In your first example, it will be looking in the tests collection for documents.
In the second example, you specify that the name of the collection should be test , which is why the behavior is different.

Node/Express app hangs whenever interfacing with MongoDB, no errors given

I'm trying to create a CRUD REST API in NodeJS, Express, and Mongodb.
I did something to break all my routes where they no longer return responses. No errors, nothing in the console, etc. I'm not sure what happened, I had it working before. Through just some console.logs I figured out it was freezing whenever it interfaced with the database.
Now, when I send a post request in Postman, it just hangs with 'Loading request'. I'm sending my request as a raw JSON in the body and a content type of application/json; charset=UTF-8 in the header.
{"username":"zezimaUsername","rsn":"Zezima","avatar":"http://secure.runescape.com/m=avatar-rs/Zezima/chat.png"}
They seem to all be hanging once they interact with Mongodb. I have Mongodb running locally with the mongod --port 27017 and created my database with two collections (user and posts) in Mongodb Compass.
I setup my db in a db.js file...
var mongoose = require('mongoose');
var url = 'mongodb://localhost:27017/my-group';
mongoose.connect(url);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error: '));
module.exports = db;
And start my app with my server.js...
var express = require('express');
var api = require('./api');
var app = express();
app.use(express.json());
app.use('/api', api);
//Error handling, don't return stack trace to user, log in console.
app.use(function (err, req, res, next){
console.log(err.stack);
res.status(500).send('Something went wrong, internal server error.');
});
app.listen(3000, function(){
console.log("Listening on port 3000");
});
And define my routes in my api.js file...
var express = require('express');
var router = express.Router();
var User = require('./db/models/User');
var Post = require('./db/models/Post');
router.post('/register', function(req, res){
var user = new User(req.body);
user.save()
.then(function(item){
res.status(200).send({message: "User successfully created.", status: 200});
})
.catch(function(err){
res.status(400).send({message: "User failed to save to database", status: 400});
});
});
router.get('/user/:username', function(req, res){
var query = User.findOne({"username": req.params.username});
query.exec(function(err, user){
if(user === null){
res.status(404).send({message: "User not found", status: 404});
}else{
res.status(200).send(user);
}
});
});
router.post('/create_post', function(req, res){
var post = new Post(req.body);
post.save()
.then(function(item){
res.status(200).send({message: "Post successfully created.", status: 200});
})
.catch(function(err){
console.log(err);
res.status(400).send({message: "Post failed to save to database", status: 400});
});
});
router.get('/post/id/:id', function(req, res){
var query = Post.findOne({"_id":req.params.id});
query.exec(function(err, post){
if(post === null){
res.status(404).send({message: 'Post not found', status: 404});
}else{
res.status(200).send(post);
}
});
});
router.get('/post/boss/:boss', function(req, res){
var query = Post.find({"boss":req.params.boss});
query.exec(function(err, post){
if(post === null){
res.status(404).send({message: 'Post not found', status: 404});
}else{
res.status(200).send(post);
}
});
});
module.exports = router;
And just to be complete...my models look like...
User.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
username:{
type: String,
required: true
},
rsn:{
type: String,
required: true
},
avatar:{
type: String,
required: true
},
posts:[{
type: Schema.Types.ObjectId,
ref: 'posts'
}]
});
var user = mongoose.model('users', userSchema);
module.exports = user;
and Post.js
var mongoose = require('mongoose');
var shortid = require('shortid');
var Schema = mongoose.Schema;
var postSchema = new Schema({
_id:{
type: String,
default: shortid.generate
},
username:{
type: Schema.Types.ObjectId,
ref: 'users'
},
rsn:{
type: String,
required: true
},
avatar:{
type: String,
required: true
},
boss:{
type: String,
required: true
}
});
var post = mongoose.model('posts', postSchema);
module.exports = post;
I'm not sure what's happening, I keep reading a bunch of various tutorials and the documentation but I'm just not seeing the issue I'm having.
You have not required your db.js file in your server.js file.
Require it after var express = require('express');
let db = require("./db");
Then it will work fine.

Unhandled promise Rejection (rejection id: 1) - Node.js

I'm new to Node.js and trying to figure out of some problems.
I've defined a signup function on a Node.js server for an Android app who writes user's info on MongoDB.
server.js
var express = require('express'),
app = express(),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
Task = require('./api/models/serverModel'),
bodyParser = require('body-parser');
var url = "mongodb://localhost:27017/ProjectDB";
mongoose.Promise = global.Promise;
mongoose.connect(url);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var routes = require('./api/routes/serverRoute');
routes(app);
app.listen(port);
console.log('Project RESTful API server started on: ' + port);
serverModel
var UserSchema = new mongoose.Schema({
userName: {type: String, unique: true, required: true},
email: {type: String, unique: true, required: true},
password: {type: String, required: true},
createdAt: {type: String, required: true}
});
var User = mongoose.model('User', UserSchema);
module.exports = User;
serverRoute
module.exports = function(app) {
var Project = require('../controllers/serverController');
// Project Routes
app.route('/signup')
.post(Project.signup);
};
serverController
...
mongoose.Promise = global.Promise;
exports.signup = function(req, res) {
return new Promise( function(resolve,reject) {
var user = new User({
userName: req.body.name,
password: req.body.pass,
mail: req.body.email,
createdAt : new Date()
});
user.save()
.then(function() { resolve({ status: 201, message: 'User Registered Successfully !' })})
.catch(function(err) {
if (err.code == 11000) {
reject({ status: 409, message: 'User Already Registered !' });
} else {
reject({ status: 500, message: 'Internal Server Error !' });
}
});
})};
...
It compiles without any error.
When I try to send a JSON via Postman like this:
{
"userName" : "username",
"email" : "user.name#gmail.com",
"password" : "blabla1"
}
it reports
UnhandledPromiseRejectionWarning: Unhandled promise Rejection (rejection id: 1) [object Object]
I've read tons of posts but I can't get out of this.
Any help?
Thanks.
Try this and revert.
server.js
var express = require('express'),
app = express(),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
Task = require('./api/models/serverModel'),
bodyParser = require('body-parser');
var url = "mongodb://localhost:27017/ProjectDB";
mongoose.Promise = global.Promise;
mongoose.connect(url);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var routes = require('./api/routes/serverRoute');
//change
//routes(app);
app.use('/',routes);
app.listen(port);
console.log('Project RESTful API server started on: ' + port);
serverRoute
var express = require('express');
var router = express.Router();
// GET home page.
router.post('/signup', function(req, res, next) {
var Project = require('../controllers/serverController');
Project.signup().then(function(result){
res.send(result);
}).catch(function(err){
res.send(err);
});
});
module.exports = router;

Mongoose populate find array of ObjectId

I'm trying to populate an array of ObjectIds when doing a find with Mongoose.
Here is the models/comment.js:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// set up a mongoose model
var CommentSchema = new Schema({
comment: {
type: String,
unique: false,
required: true
},
date: {
type: Date,
default: new Date()
},
});
module.exports = mongoose.model('Comment', CommentSchema);
Here is the models/question.js:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Comment = require('./comment');
// set up a mongoose model
var QuestionSchema = new Schema({
title: {
type: String,
unique: false,
required: true
},
question: {
type: String,
required: true
},
plus: {
type: Number,
required: true,
default: 0
},
minus: {
type: Number,
required: true,
default: 0
},
date: {
type: Date,
default: new Date()
},
comments:[
{type: Schema.Types.ObjectId, ref: 'Comment'}
]
});
module.exports = mongoose.model('Question', QuestionSchema);
Here is index.js
var express = require('express');
var app = express();
var request = require('request-promise');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');
var config = require('./config/database'); // get db config file
var User = require('./models/user'); // get the mongoose model
var Room = require('./models/room'); // get the mongoose model
var Comment = require('./models/comment'); // get the mongoose model
var Question = require('./models/question'); // get the mongoose model
var port = process.env.PORT || 5000;
var jwt = require('jwt-simple');
var http = require('http');
var io = require('socket.io');
var server = http.createServer(app);
var io = io.listen(server);
// get our request parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// log to console
app.use(morgan('dev'));
// Use the passport package in our application
app.use(passport.initialize());
// Set the port
app.set('port', port);
//App files located in /public
app.use(express.static(__dirname + '/public'));
// views is the directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
// The root url of the website serves the Angular app
app.get('/', function (request, response) {
response.render('pages/index');
});
// connect to database
mongoose.connect(config.database);
// pass passport for configuration
require('./config/passport')(passport);
var roomService = require('./controllers/roomservice.js');
roomService.setup(io);
// connect the api routes under /api/*
app.use('/api', apiRoutes);
// Start the Express app
server.listen(app.get('port'), function () {
console.log('Node app is running on port', app.get('port'));
});
Here is controllers/roomservice.js
function RoomService(){
var socketio;
var Comment = require('../models/comment'); // get the mongoose model
var Question = require('../models/question'); // get the mongoose model
var Room = require('../models/room'); // get the mongoose model
function setup(io){
socketio = io;
socketio.on("connection", function(socket){
socket.on('joinRoom', function(msg){
console.log("joinRoom");
socket.join(msg.room)
Question.find({})
.exec(function(err, questions) {
for(var question in questions){
for(var comment in questions[question].comments){
questions[question].comments[comment] = Comment.find({ "_id": questions[question].comments[comment]});
}
}
socket.emit("listQuestions", questions)
});
});
socket.on('addQuestion', function(msg){
console.log("addQuestion");
var question = new Question({
title: msg.title,
question: msg.question
});
// save the question
question.save(function(err) {
if (err) throw err;
io.to(msg.room).emit("addQuestion", question);
});
});
socket.on('addComment', function(msg){
var comment = new Comment({
comment: msg.comment
});
// save the comment
Question.findOne({_id: msg.question}, function(err, question){
if (err) throw err;
question.comments.push(comment);
question.save(function(err) {
if (err) throw err;
io.to(msg.room).emit("addComment", comment);
console.log(question);
});
});
});
socket.on('addPlus', function(msg){
// save the comment
Question.findOne({_id: msg.question}, function(err, question){
if (err) throw err;
question.plus = question.plus + 1;
question.save(function(err) {
if (err) throw err;
io.to(msg.room).emit("addPlus", question);
});
});
});
socket.on('addMinus', function(msg){
// save the comment
Question.findOne({_id: msg.question}, function(err, question){
if (err) throw err;
question.minus = question.minus + 1;
question.save(function(err) {
if (err) throw err;
io.to(msg.room).emit("addMinus", question);
});
});
});
});
}
return{
setup: setup
}
}
module.exports = new RoomService();
I'm trying to populate the array of comments when returning the list of questions. I tried it with the populate method from Mongoose but it returns an empty array of comments.
Question.find({}).populate("comments")
.exec(function(err, questions) {
socket.emit("questions", questions)
});
When I don't put the populate method I get something like this :
[{"title": "test", "comments": ["1253454", "654654747"]},
{"title": "test", "comments": ["1253454", "654654747"]}]
But I want something like this :
[{"title": "test", "comments": [{"comment": "test"}, {"comment": "test2"}]},
{"title": "test", "comments": [{"comment": "test"}, {"comment": "test2"}]}]
What am I doing wrong?
What is your mongoose version? The version 4.7.1 is fine for me:
import { connDb } from './base';
import { model, Schema, SchemaTypes, disconnect } from 'mongoose';
const Question = model<any>('Question', new Schema({
title : SchemaTypes.String,
comments: [
{
type: SchemaTypes.ObjectId,
ref : 'Comment',
},
],
}))
const Comment = model<any>('Comment', new Schema({
comment: SchemaTypes.String,
}))
connDb().then(() => Promise.all([
Comment.remove({}),
Question.remove({}),
])).then(() => Comment.insertMany([
{
comment: 'hello',
},
{
comment: 'world',
}
])).then((data: any[]) => Question.insertMany([
{
title : 'question',
comments: data.map((item: any) => item._id),
}
])).then(() => Question.find({}).populate('comments').exec()).then((d) => {
console.log(JSON.stringify(d))
}).then(() => disconnect())
The result is:
+ ts-node ./src/__test__/pop_comment.ts
[{"_id":"5846322e69db6c1ec86ac5fd","__v":0,"title":"question","comments":[{"_id":"5846322e69db6c1ec86ac5fb","__v":0,"comment":"hello"},{"_id":"5846322e69db6c1ec86ac5fc","__v":0,"comment":"world"}]}]

Node.Js mongoose find not working

I'm trying to get the documents from my MongoDB by using mongoose "find" method. But I'm not able to get records. It did not returns any error. Here is my code
Server.js
var express = require('express');
var bodyparser = require('body-parser');
var mongoose = require('mongoose');
var cors = require('cors');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
mongoose.promise = global.promise;
mongoose.connect("mongodb://localhost:27017/testdb");
app.use(bodyparser.json());
app.use(cors());
app.use(express.static(__dirname + 'server'));
var api = require('./routes/apihandler')(app, express, io);
app.use('/alerts', api);
http.listen(3000, function(err){
if(err) {
console.log(err);
} else {
console.log('Listening PORT' + config.port);
}
});
apihandler.js
var request = require('request');
var express = require('express');
var alertRoutes = require('../../services/routes/alertRoutes');
var api = express.Router();
module.exports = function(app, express, io){
api.get('/getAllAlerts/:retailerId/:loyaltyId', getAllAlerts);
return api;
}
function getAllAlerts(req, res, callback) {
console.log('apihandler');
try {
alertRoutes.getAllAlerts(req,res,callback);
}
catch(err) {
res.send({"status" : "error", message: err.mes});
}
}
Manager.js
var alertModel = require('./../models/alertModel');
alertModel.find({}, function (err, docs) {
console.log(err);
console.log(docs);
});
Model.js
var mongoose = require('mongoose');
var alertSchema = new mongoose.Schema({
id:{ type: String },
alertType:{ type: Number},
retailerId: { type: String },
loyaltyId: { type: String },
email: { type: String },
description: { type: String},
locationId:{type: String },
reason:{type: String},
reasonDescription:{type: String},
capturedReasonsList:mongoose.Schema.Types.Mixed
},{ collection: 'alerts' });
module.exports = mongoose.model('alerts', alertSchema);
alertRoutes.js
//Get all Alerts
function getAllAlerts(req, res, callback){
console.log('getAllAlerts');
=
var srchData = {
retailerId:req.params.retailerId,
loyaltyId:req.params.loyaltyId
};
retailerId='+req.params.retailerId+'&loyaltyId='+req.params.loyaltyId;
alertManager.getAlert(srchData,function(err,alertDetails){
console.log('alertDetails',alertDetails);
if (err) throw err;
if(alertDetails && alertDetails.length > 0){
res.status(200).send(alertDetails);
}else{
res.status(200).send({success: false,message: 'Alert Details not Found'});
}
});
// });
}
I can able to get into Manager js. But the find query is not working
Please Help me to resolve this issue.
Thank you.
Try these codes. I am working with these codes & it works for me.
Model :
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var alertSchema = mongoose.Schema({
id:{ type: String },
alertType:{ type: Number},
retailerId: { type: String },
loyaltyId: { type: String },
email: { type: String },
description: { type: String},
locationId:{type: String },
reason:{type: String},
reasonDescription:{type: String},
capturedReasonsList:mongoose.Schema.Types.Mixed
});
mongoose.model('Alert',alertSchema);
Server Code :
var mongoose = require('mongoose');
var alertModel = mongoose.model('Alert');
alertModel.find().exec(function (err, docs) {
if(!err)
console.log(docs);
});
Maybe the find is just never called... Do some console.log before the find to make sure.
Provide the code of "getAlert", we cannot see where and how Manager.js is used.

Resources