MongoError: not authorized for query - node.js

I have a small Node.js/ Express/ Mongoose app which I have running on an AWS - EC2 instance built using Bitnami AMI, whenever I try to run .find on my app MongoDB collection using Chrome Postman I get the following result.
{
"name": "MongoError"
}
[MongoError: not authorized for query on projectDB.areas]
I tried using the following 3 connection strings but all 3 returned the same result, can someone please help by telling me what I am missing / doing wrong here? Thanks
var connectionString = 'mongodb://localhost:27017/'+dbName;
var connectionString = 'mongodb://root:bitnami#localhost:27017/'+dbName;
var connectionString = 'mongodb://root#localhost:27017/'+dbName;
My node.js app code:
area.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var areaSchema = new Schema({
name: { type: String, required: true },
});
module.exports = mongoose.model('Area', areaSchema);
areas.js
var Area = require('../app/models/area');
var express = require('express');
var router = express.Router();
router.route('/').get(function(req, res){
Area.find(function(err, areas){
if(err){
return res.send(err);
}
res.json(areas);
//res.send({sucess:true, areas:areas})
});
});
app.js
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var areas = require('./routes/areas');
var app = express();
app.set('port', process.env.PORT || 8080);
app.use(bodyParser.json({ type: 'application/*+json' }));
var dbName = 'projectDB';
var connectionString = 'mongodb://localhost:27017/'+dbName;
// var connectionString = 'mongodb://root:bitnami#localhost:27017/'+dbName;
// var connectionString = 'mongodb://root#localhost:27017/'+dbName;
////////Tried the above 3 connection strings, none worked...
mongoose.connect(connectionString, function(err){
if(err){
throw err;
}
});
var corsOptions = {
origin: '*',
allowedHeaders: ['Content-Type'],
methods: ['POST','GET','PUT','DELETE'],
credentials: true
};
app.use(cors(corsOptions));
app.use('/api/areas', areas);
module.exports = app;
www.js
var app = require('../app');
var server = app.listen(app.get('port'), function(){
console.log('Server running on port: '+ server.address().port);
});

Since, running $ mongo admin --username root --password bitnami didn't take you into a Mongo shell.
Assuming that you ran that code on the server and not your local machine, this only means your MongoDB has not been properly setup. You should probably remove the instance completely from AWS and start setting up from scratch. Otherwise, simply follow the instructions on MongoDB website to install MongoDB.
Also, for Node.js use the following code to ensure that you have actually connected:
`
mongoose.connect("mongodb://root#localhost:27017/projectDB");
var db = mongoose.connection;
db.once('open', function () {
console.log('MongoDB connection successful.');
});
`

Related

Mongoose find query is not executing

I am trying to fetch some data from a mongodb. I am able to fetch the details from the model MyModel (defined in Server.js). But I can't execute the find method in the model Skill (defined in Skill.js).
Server.js
let express = require('express');
let app = express();
var config = require('./config/config');
let bodyParser = require('body-parser');
var mongoose = require('mongoose');
var cors = require('cors')
var path = require("path");
let Skill = require('./app/models/Skill');
const dbURI = config.dbURI;
app.use(cors());
app.use(bodyParser.json(true));
mongoose.connect(dbURI, {useNewUrlParser: true});
mongoose.connection.on('connected', function () {
console.log("Connected");
});
var MyModel = mongoose.model('Test', new Schema({ name: String
}));
Skill.findOne(function(error, result) {
console.log("1",error,result);
});
MyModel.findOne(function(error, result) {
console.log("2",error,result);
});
app.listen(config.appPort,function () {
console.log('App running on port :: "' + config.appPort.toString() + '"');
});
app/models/Skill.js
var mongoose = require('mongoose');
var skillSchema = new mongoose.Schema({
name: String,
length: String,
});
var Skill = mongoose.model('Skill', skillSchema,'Skill');
module.exports = Skill;
Output
App running on port :: "8080"
Conneccted
2 null { _id: 5c6678215c50a65e59fc6a89, name: 'test', __v: 0 }
I haven't found any issues while creating the schema. Could someone help me to resolve the issue?
I can't test my suggestion at the moment, but one thing I noticed in your code is that you queries, as in
Skill.findOne(function(error, result) {
console.log("1",error,result);
});
MyModel.findOne(function(error, result) {
console.log("2",error,result);
});
are not executed in the "connected" callback; may be it's not the main problem, but I would try to change the code as follows:
mongoose.connection.on('connected', function () {
console.log("Connected");
Skill.findOne(function(error, result) {
console.log("1",error,result);
});
MyModel.findOne(function(error, result) {
console.log("2",error,result);
});
});
The key thing is that each call (.on, .findOne) starts a promise, which encapsulates an asynchronous behaviour. I you place ,findOne invocation just after .on invocation, you can't be sure Mongoose's connection is ready when you starts .findOne...

I can't save or find a document into MongoDB using Mongoose

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

Node.js Mongoose model not saving without error

Making this simple Node.js Express API I encountered an odd problem:
I am creating a model and inserting data into it and then saving it to my MongoDB. But the record is never saved but I also don't get any error. I have checked if MongoDB is running and both syslog for Node errors and mongod.log for MongoDB errors as well as my own Wilson debug.log file. All contain no errors.
I use postman to test the API and do get a response every time. It's just that the data does not get saved to MongoDB (I used the mongo console with db.collection.find() to check for inserted records).
Any idea why this could be happening?
my code:
api.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var http = require('http');
var https = require('https');
var fs = require('fs');
var winston = require('winston');
// Configure logging using Winston
winston.add(winston.transports.File, { filename: '/home/app/api/debug.log' });
winston.level = 'debug';
// Request body parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Enable https
var privateKey = fs.readFileSync('path to private key');
var certificate = fs.readFileSync('path to cert file');
var credentials = {
key: privateKey,
cert: certificate
};
// ROUTERS
var router = express.Router();
var speciesRouter = require('./app/routes/speciesRouter');
router.use('/species', speciesRouter);
// Routes prefix
app.use('/api/v1', router);
// SERVER STARTUP
http.createServer(app).listen(3000);
https.createServer(credentials, app).listen(3001);
speciesRouter.js
var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();
var Sighting = require('../models/sighting');
var winston = require('winston');
// Database connection
var dbName = 'dbname';
mongoose.connect('mongodb://localhost:27017/' + dbName);
var db = mongoose.connection;
db.on('error', function(err){
winston.log('debug', err);
});
router.route('/')
.post(function(req, res) {
var sighting = new Sighting();
sighting.user_key = req.body.user_key;
sighting.expertise = req.body.expertise;
sighting.phone_location = req.body.phone_location;
sighting.record_time = req.body.record_time;
sighting.audio_file_location = '/var/data/tjirp1244123.wav';
sighting.probable_species = [{species_name:'Bosaap', percentage:100}];
var error = '';
winston.log('debug', 'test');
// This does not get execute I suspect..
sighting.save(function(err) {
winston.log('debug', 'save');
if (err) {
winston.log('debug', err);
error = err;
}
});
res.json({
probable_species: probable_species,
expertise: req.body.expertise,
error: error
});
});
module.exports = router;
sighting.js (model)
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SightingSchema = new Schema({
user_key: String,
expertise: Number,
phone_location: { lat: Number, lng: Number },
record_time: Number,
audio_file_location: String,
probable_species: [{ species_name: String, percentage: Number }]
});
module.exports = mongoose.model('Sighting', SightingSchema);
Did you try updating your mongodb.
sudo npm update
You can try using promise.
return sighting.save().then(function(data){
console.log(data); // check if this executes
return res.json({
probable_species: probable_species,
expertise: req.body.expertise,
error: error
});
}).catch(function(err){
console.log(err);
});
One more thing dont use res.json outside the save function because in async code it will run without waiting for save function to complete its execution

TypeError: Object #<Object> has no method 'find'

I follow actually a training in nodejs, express and mongo.
I developed a rest webservice but when I try to access it, I have the current exception :
TypeError: Object # has no method 'find'
I don't understand what's happen exactly because my code seems correct and the same that in the tutorial.
Schema Definition
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var bookModel = new Schema({
title:{
type:String
},
author:{type:String},
genre:{type:String},
read:{type:Boolean,default:false}
});
module.export= mongoose.model('Book',bookModel);
Definition of my service
var express = require('express'),
mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/bookAPI');
var Book = require('./models/bookModel');
var app = express();
var port = process.env.PORT || 3000;
var bookRouter = express.Router();
bookRouter.route('/books')
.get(function(req,res){
Book.find(function(err,books){
if(err)
console.log(err);
else
res.json(books);
});
});
app.use('/api', bookRouter);
app.get('/',function(req,res){
res.send('welcome to my api 2000');
})
app.listen(port, function(){
console.log('Running on PORT: ' +port);
});
try this:
var Book= mongoose.model('Book',bookModel);
export module like this:
module.exports = {
Book: Book
};
And import with following code:
var Book = require('./models/bookModel').Book;
after that write find query
Book.find({},function(err,books){
if(err)
console.log(err);
else
res.json(books);
});

Mongo models not responding

I'm working on a new app and trying to get mongo set up locally for storage. My api endpoints are getting hit but as soon as I try to actually call a db operation - find or save - it doesn't respond.
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var Person = require('./data/person');
var dbConfig = require('./config');
//database: 'mongodb://localhost:27017/persondb'
var db = mongoose.createConnection(dbConfig.database);
db.on('error', function() {
console.info('Error: Could not connect to MongoDB. Did you forget to run `mongod`?');
});
if (~process.argv.indexOf('mode_dev')) {
global.mode_dev = true;
console.log('Server started in dev mode.');
}
// 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());
app.use('/api', router);
router.route('/persons')
.post(function(req, res) {
debugger;
var person = new Person(); // create a new instance of the Person model
person.name = req.body.name;
person.save(function(err) {
debugger;
if (err)
res.send(err);
res.json({ message: 'Person created!' });
});
})
.get(function(req, res) {
Person.find(function(err, persons) {
debugger;
if (err)
res.send(err);
res.json(persons);
});
});
Here's the schema:
data/item.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var personSchema = new Schema({
name: String,
});
module.exports = mongoose.model('Person', personSchema);
I am running mongod before getting my webserver started. As soon as I get to the .save or .find calls, no error is thrown but the callbacks are never hit.
I would connect like this:
mongoose.connect("mongodb://localhost/persondb");
var db = mongoose.connection;
maybe this will help it explains problems using mongoose.createConnection(
if you use createConnection, you need to always reference that connection variable if you include a registered model, otherwise if you use mongoose to load the model, it will never actually talk to your database.
The other solution is to simply use mongoose.connect instead of
mongoose.createConnection. Then you can just use
mongoose.model(‘MyModel’) to load the requested model without needing
to carry around that db connection variable.

Resources