I have a strange issue with MongoDB-mongoose, which does not respond to REST API
mongoose version - 4.11.3
Mongo DB shell version 3.4.6
Everything is local on my computer
Connection to Mongo DB is the following:
server.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("Connected correctly to db");
});
...
var app = express();
var tasks = require('./server/routes/taskRouter');
app.use('/api/tasks',tasks);
The log "Connected correctly to db" is printed.
Schema (tasks.js)
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var taskSchema = new Schema({
name: String
});
var Task = mongoose.model('Task', taskSchema);
module.exports = Task;
And finally taskRouter.js
var express = require('express');
var bodyParser = require('body-parser');
var Task = require('../models/tasks');
var taskRouter = express.Router();
taskRouter.use(bodyParser.json());
taskRouter.route('/')
.get(function (req, res, next) {
Task.find({}, function (err, task) {
console.log("result"+task)
if (err) throw err;
res.json(task);
});
})
.post(function (req, res, next) {
var task = new Tasks();
console.log ('the name is '+req.body.name);
task.name = req.body.name;
task.save(function(err){
console.log ("arrived there");
if (err)
res.send(err);
res.json({message: "Task created"});
});
})
As you see, everything is by the book .
But I never get any logs from task.save and Task.find
My 'morgan' logger shows just the following logs:
GET /api/tasks - - ms - -
POST /api/tasks - - ms - -
Postman is stuck on "Loading", until receives a timeout: Could not get any response.
All simple operation on the tasks collection in Mongo DB shell are performed without any problem.
What happens with mongoose?
Thanks in advance.
Try to create a separate file config.js with the following code :
module.exports = {
'database': 'mongodb://localhost:27017/yourdatabasename'
}
server.js:
...
var config = require('./config'); // get our config file
...
var mongoose = require('mongoose');
...
mongoose.connect(config.database, { useMongoClient: true });
mongoose.connection.on('open', function(err, doc){
console.log("connection established");
var app = express();
var tasks = require('./server/routes/taskRouter');
app.use('/api/tasks',tasks);
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("Connected correctly to db");
});
Related
i have a pre-existing collection (which is on mongodb atlas), and i've connected it and cerate Modules and Schemas, and i can console log it , so far so good, but when i export the module to index.js i can't console log the data it say Model.find is not a fucntion.
PS.
i'm new to this
My code:
var mongoose = require('mongoose');
var uri = 'mongodb+srv://USER:PASSWORD#wt-cluster-xd7ou.mongodb.net/test?
retryWrites=true'
mongoose.connect(uri, {dbName: 'dbName'});
mongoose.Promise = global.Promise;
var connection = mongoose.connection;
connection.on('error', console.error.bind(console, 'connection error:'));
connection.once('open', function () {
var menuSchema = new mongoose.Schema({
_id: mongoose.Schema.ObjectId,
category: String,
food_name: String,
food_desc: String,
food_price: String
});
var Menu = mongoose.model('Menu', menuSchema, 'menu');
Menu.find(function(err, menus){
if(err) return console.err(err);
console.log(menus);
})
module.exports = Menu;
});
this console log my data correctly
index.js
var express = require('express');
var router = express.Router();
var Menu = require('../models/menu')
var assert = require('assert')
/* GET home page. */
router.get('/', function(req, res, next) {
Menu.find({}, function (err,menus) {
assert.equal(err,null);
res.send(menus);
});
});
module.exports = router;
here is where i'm trying to send the data to the HTML
It appears you are defining and exporting your model inside the connection.on() function. Try defining those in a separate file and see if that helps.
Create your model in a separate file.
var mongoose = require('mongoose');
let connection = require('connnection.js')
var menuSchema = new mongoose.Schema({
_id: mongoose.Schema.ObjectId,
category: String,
food_name: String,
food_desc: String,
food_price: String
});
var Menu = mongoose.model('Menu', menuSchema, 'menu');
Menu.find(function(err, menus){
if(err) return console.err(err);
console.log(menus);
})
module.exports = Menu;
Change your db connection to
var mongoose = require('mongoose');
var uri = 'mongodb+srv://USER:PASSWORD#wt-cluster-xd7ou.mongodb.net/test?
retryWrites=true'
mongoose.connect(uri, {dbName: 'dbName'});
mongoose.Promise = global.Promise;
var connection = mongoose.connection;
connection.on('error', console.error.bind(console, 'connection error:'));
connection.once('open', function(){
console.log('Database ready.')
})
module.exports = connection
Save this as connection.js for require to work.
Test the route again.
I'm using nodeJS for the first time, and I'm trying to do an application that connects to MongoDB via Mongoose.
I've installed MongoDB, NodeJS and Mongoose(via npm) successfully.
My problem is:
When I connect my node application through mongoose does not show any error, but when I try to insert a document, it just doesn't do anything at all. Freezes at the save line.
This is my code
var express = require('express');
var app = express();
var mongoose = require('mongoose');
...
mongoose.connect('mongodb://127.0.0.1:27017/exampleDB');
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
var someModel = mongoose.model('someModel', {
name : String
});
app.get('/api/todos', function(req, res) {
var awesome_instance = new someModel({ name: 'awesome' });
console.log("about to save the document");
awesome_instance.save(function (err) {
if (err) return handleError(err);
});
});
app.post('/api/todos', function(req, res) {
});
...
app.listen(8080);
console.log("App listening on port 8080");
Using a mongo client I can see my db, but not the collection that the code should have created. Also my mongoDB detects the connection from nodeJS. I just don't know what could be happening.
This is what my server.js (node) is showing
$ node server.js
App listening on port 8080
about to save the document
GET /api/todos - - ms - -
This is my mongo client
$ ./mongo
MongoDB shell version v4.0.0
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 4.0.0
use exampleDB
switched to db exampleDB
show collections
exampleCollection
Thanks a lot in advance.
Let your get this and see if it works.
var express = require('express');
var app = express();
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/exampleDB', { useNewUrlParser: true });
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
var someModel = mongoose.model('someModel', {
name : String
});
app.get('/api/todos', async function(req, res) {
var awesome_instance = new someModel({ name: 'awesome' });
await awesome_instance.save()
});
app.post('/api/todos', function(req, res) {
});
app.listen(8080, ()=>console.log("App listening on port 8080"));
I have my file to add data to mongo via mongoose :
var mongoose = require('mongoose');
var mongoDB = 'mongodb://myuser:mypass#ds145293.mlab.com:45293/employees';
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'))
db.once('open',function(){
console.log('connected')
var kittySchema = mongoose.Schema({
name: String
});
var Kitten = mongoose.model('Kitten', kittySchema);
var fluffy = new Kitten({ name: 'fluffy' });
fluffy.save(function (err, fluffy) {
if (err) return console.error(err);
console.log('saved');
});
})
mongoose.connection.close()
Copied almost verbatim from mongoose site.I am able to connect to the database but i dont get the 2nd console log.I have a db but no collections.Is this the problem?
Replace mongoose.Schema with new Schema and also I don't think this mongoose.Promise = global.Promise is required.
It cant complete the save before you close the database. There are many options to wait for the save. I like async/await.
edit: sorry that was too quick. Updated example.
var mongoose = require('mongoose');
var mongoDB = 'mongodb://localhost/something';
async function run() {
await mongoose.connect(mongoDB);
console.log('connected')
var kittySchema = new mongoose.Schema({ name: String });
var Kitten = mongoose.model('Kitten', kittySchema);
var fluffy = new Kitten({ name: 'fluffy' });
await fluffy.save();
console.log('saved');
mongoose.connection.close();
}
run();
Or you can just move the close to after you have saved:
var mongoose = require('mongoose');
var mongoDB = 'mongodb://localhost/something';
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'))
db.once('open', function () {
console.log('connected')
var kittySchema = new mongoose.Schema({name: String });
var Kitten = mongoose.model('Kitten', kittySchema);
var fluffy = new Kitten({ name: 'fluffy' });
fluffy.save(function (err, fluffy) {
if (err) return console.error(err);
console.log('saved');
mongoose.connection.close();
});
})
I am new to nodejs and express.When i try to do get request from the mongoose database in mlab.com i get an empty response.
my serve code is (app.js),
var express = require('express');
var mongoose = require('mongoose');
var app = express();
var db =mongoose.connect('mongodb://test:test#ds155695.mlab.com:55695/app');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('we are connected');
});
var user = require('./model/userModel');
var routers = express.Router();
routers.route('/getUSers').get(function(req,res){
user.find(function(err,users){
if(err) {
console.log(err);
} else {
res.json(users);
}
});
});
app.use('/api',routers);
app.listen(8000,function() {
console.log('server working');
});
My model is userModel.js
var mongoose = require('mongoose');
var app = mongoose.Schema({
firstName : String,
lastName : String
});
module.exports = mongoose.model('users',app);
can anyone help me where am i going wrong !
I am new to node.js . I am trying to create one connection in server.js and use it in addAcction.js but got error while running "Software is not
a constructor", Please help me this?
//Server .js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/MSDN');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error'));
db.once('open', function callback() {
console.log("Connection with database succeeded.");
});
module.exports = db;
var SoftwareSchema = new mongoose.Schema({
SoftwareID: Number,
SoftwareName: String,
});
module.exports = mongoose.model('Software', SoftwareSchema);
//addAction.js
var Software = require('./Server').Software;
var Software1 = new Software({
SoftwareID : 1,
SoftwareName : "MNG123",
});
Software1.save(function(err){
if ( err ) throw err;
console.log("Software Saved Successfully");
});