getting empty array in response res.json(); in nodejs code - node.js

Why does res.json respond with an empty array?
I want to get all data from collection distributor ,so for that I have
created model file and then assigned it to on variable Distributordata
Server file : app.js
var express=require('express');
var app=express();
var bodyParser=require('body-parser');
var mongoose=require('mongoose');
var Distributordata=require('./distributor.model');
var db='mongodb://localhost/Distributordata';
mongoose.connect(db);
var port=8080;
app.get('/',function(req,res){
res.send("happy to be here");
});
app.get('/distributor',function(req,res){
// res.send("hi from distributors")
console.log("getting all distributors");
Distributordata.find(function(err,distributordata){
if(err){
res.send("error has occured");
}
else{
console.log(distributordata);
res.send(distributordata);
}
});
});
app.listen(port,function(){
console.log('app listening on port'+port);
});
Model file : distributor.model.js
var mongoose=require('mongoose');
var Schema = mongoose.Schema;
var DistributorSchema=new Schema({
dname:String,
daddress: String
});
module.exports=mongoose.model('Distributordata',DistributorSchema);
output
on cmd:
app listening on port8080
getting all distributors
[ ]

So far I've understood your problem is you are creating your collection in mongodb by yourself as the collection name distributor. And also as you are not sending any post request so your code will not create any collection automatically in the main database.
But, by default mongoose always creates a collection name by pluralizing the name of the model, in your case this collection name would be distributordatas. But when, you are trying to get the data from your database, it's getting the collection name as distributor for this reason it becomes unable to make a connection. But you can keep this using force naming convention for collection as like you want.
In your distributor.model.js file change this line of code to this one:
module.exports = mongoose.model('Distributordata', DistributorSchema, 'distributor');
Hopefully, it'll solve your problem. For more reference check this out https://mongoosejs.com/docs/guide.html#collection

Related

Mongo Query Returning Empty Array

I'm a total beginner at this and am using a tutorial to learn the basics of the MEAN stack. I am trying to return the documnents in my database to a web page but am instead receiving an empty array.
I have created a cluster on Mongodb Atlas called mytasklist. Inside here I created a database called mytasklistdb. Inside this I have a table (object) called mytasklistdb.mytasklisttutorial. My understanding of this is limited and so maybe I'm making a huge error somewhere here. I have experience of SQL but not Mongo and so the whole 'clusters' and 'collections' thing is new to me.
Anyway my code is as follows. I took the string for the database connection from the Mongo connection tab.
var express = require('express');
var router = express.Router();
var mongojs = require('mongojs');
var db = mongojs('mongodb+srv://myusername:mypassword#mytasklist-qx0ka.mongodb.net/test?retryWrites=true&w=majority', ['mytasklisttutorial']);
router.get('/tasks', function(req, res, next){
db.mytasklistdb.find(function(err, tasks){
if(err){
res.send(err);
}
res.json(tasks);
});
});
module.exports = router;
My database objects look like this:
_id:5db5f1f31c9d440000c3e7fe
title:"Walk the dog" - this is a string
isDone:false - this is boolean
I'm just getting an empty array but in the tutorial the guy is getting these 'documents'. What am I doing wrong?
EDIT: I realised that the 'tasks' part of the tutorial example was relating to a database called 'tasks'. Mine is called 'mytasklistdb'. I therefore changed this. I also added a parameter with the name of my collection to the line passed in to mongojs.
I have changed my code above to reflect this
The solution was to replace 'task' and 'test' with the name of my db. As follows:
var express = require('express');
var router = express.Router();
var mongojs = require('mongojs');
var db = mongojs('mongodb+srv://James:Noentry1#mytasklist-qx0ka.mongodb.net/mytasklistdb?retryWrites=true&w=majority', ['mytasklisttutorial']);
router.get('/tasks', function(req, res, next){
db.mytasklisttutorial.find(function(err, tasks){
if(err){
res.send(err);
}
res.json(tasks);
});
});
module.exports = router;
My guess is that you are not passing your query, just the callback in the find() method, probably you need to do something like this:
db.tasks.find({},function(err, tasks){
if(err){
res.send(err);
}
res.json(tasks);
});

How does mongoose model connect with mongodb?

I have structured a user collection using mongoose.model().This model exist in seperate file called as model\user.js. The mongodb connection instance (using mongoose) exist in seperate file db\mongoose.js. Both of these files are imported into server.js to work with web application.
var express = require('express');
var bodyParser = require('body-parser');
var {mongoose} = require('./db/mongoose');
var {User} = require('./models/user');
var app = express();
app.use(bodyParser.json());
app.post('/todos', (req, res) => {
var user = new User({
text: req.body.text
});
user.save().then((doc) => {
res.send(doc);
}, (e) => {
res.status(400).send(e);
});
});
app.listen(3000, () => {
console.log('Started on port 3000');
});
module.exports = {app};
The {mongoose} and {User} seems to be a separate entities and model\user.js didn't import ./db/mongoose.js as well . The user model being static content , how does user.save() connects with db and save the document?
First of all let me tell you what is happening in your project.
in Mongoose file:
You have DB connection with Mongoose.
Now Mongoose has your DB connection.
That is the reason it is imported in server.js file.
Secondly, in you model/user.js you have
Declared Schema using Mongoose.
user.save method.
When you use Mongoose here (or any DB related query), it points to your connected DB. Which does not require any explicit connection written in some file.
For more details read Mongoose Docs.
Hope I cleared your thoughts.

Listing users from Database using Node.js and Mongoose

I am trying to load data from my database named users which contains 2 users in the collection named userlist. Each entry has a name and age.
The code below resides in my app.js.
//set database connection
mongoose.connect('mongodb://localhost:27017/users');
mongoose.connection.on('error',function(){
console.log('MongoDB Connection Error. Please make sure that MongoDB is running');
process.exit(1);
});
mongoose.connection.once('open',function(callback){
console.log('Connected to Database');
});
var userSchema = new mongoose.Schema({
name:{type:String,uppercase:true},
age:Number
});
var userModel = mongoose.model('userModel',userSchema);
app.get('/users', function(req, res, next) {
userModel.find({},function(err,userModel){
res.send(userModel);
//Have tried res.send(userlist) also
})
});
This returns an empty set [] on localhost:3000/users. However i do have two entries in my database.
var userSchema = new mongoose.Schema({
name:{type:String,uppercase:true},
age:Number
},{collection:'userlist'});
This is what helped me.

Data not coming from database Mongodb Openshift

I have created nodejs(expressjs) application with mongodb on Openshift.
and I have pushed my database (mehendiDB) on the mongodb server which I can see on the server by using rockmongo cartridge as follows
admin(2)
api(3)
local(1)
mehendiDB(5)
Comments(10)
Likes(10)
Posts(8)
Users(9)
system.indexes(4)
Though I can see the data uploaded onto server but when I retrive it with the following code from my users.js I do not get anything but an empty array. Code I ave written in users.js is as follows
var express = require('express');
var router = express.Router();
var mongodb = require('mongodb');
router.dbServer = new mongodb.Server(process.env.OPENSHIFT_MONGODB_DB_HOST,parseInt(process.env.OPENSHIFT_MONGODB_DB_PORT));
router.db = new mongodb.Db(process.env.OPENSHIFT_APP_NAME, router.dbServer, {auto_reconnect: true});
router.dbUser = process.env.OPENSHIFT_MONGODB_DB_USERNAME;
router.dbPass = process.env.OPENSHIFT_MONGODB_DB_PASSWORD;
router.db.open(function(err, db){
if(err){ throw err };
router.db.authenticate(router.dbUser, router.dbPass, {authdb: "admin"}, function(err, res){
if(err){ throw err };
});
});
router.get('/', function (req, res){
router.db.collection('Users').find().toArray(function(err, names) {
console.log("Printing output : " + names);
res.header("Content-Type:","application/json");
res.end(JSON.stringify(names));
});
});
module.exports = router;
PS : I am not getting any errors in the log console(nodejs.log) when I checked it. and showing 'Printing output'
Thanks in advance.
Have you verified that the database name that you uploaded your data to is the same as the process.env.OPENSHIFT_APP_NAME that you are using within your application?

Creating login system in node/mongodb/express. can't connect to database

I am trying to create a login system where an admin can log in and look at data that is not available to the public. Right now I'm just trying to find my admin instance in my database. I have two node files: app.js and account_manager.js
app.js
//creates node app
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var AM = require('./account_manager');
//stuff...
/***************************************
LOGIN
***************************************/
app.post('/login', function(req, res){
AM.manualLogin(req.param('username'), req.param('password'), function(e, o){
if (!o){
res.send(e, 400);
} else{
req.session.user = o;
res.send(o, 200);
}
});
});
account_manger.js is required in app.js and is stored in AM
account_manager.js:
var express = require('express');
var app = express();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost');
var admin_db = mongoose.connection;
admin_db.on('error', console.error.bind(console, 'connection error: '));
//connection open?
admin_db.once('open', function callback(){
console.log("User Database connection open!\n");
});
var User_Schema = new mongoose.Schema({username: String, password: String});
var Admin = mongoose.model('Admin', User_Schema);
exports.manualLogin = function(user, pass, callback)
{
admin_db.find({username: user},function(err,docs){ //error is here
if(docs){
var x = 0;
var flag = false;
while(docs[x]){ //goes through all the admins
if (docs[x].param("username") == user){ //if it's a match
callback(null, docs);
flag = true;
break;
}
x+=1;
}
if (flag == false){
callback('invalid-password/username');
}
}
});
}
I get a TypeError that says:
Object #<NativeConnection> has no method 'find'
what's my problem?
I'm still quite new to node.js myself, but I'll try and answer anyway.
It looks like you've properly built your connection to mongodb through mongoose, but you have not created a schema. While mongodb doesn't have schemas, mongoose does.
What you'll need to do is create a schema (UserSchema) that matches the construction of a user document in your users collection, then create an instance of that schema (User) which is now your model, then call .find on that model.
The Mongoose Quick Start guide goes through this process:
http://mongoosejs.com/docs/index.html
EDIT after update:
You are currently calling admin_db.find. This does not exist. This is the error you are getting.
You need to change that to Admin.find. You also need to understand what the difference is.
EDIT once more:
You're not properly using the admin_db.once callback.
I suggest you go back and reread the Mongoose Quick Start guide I linked. It's quite short and goes through all of this.
I see you're rolling your own system here, but I thought I'd share a link to Drywall in case you could gain some inspiration or knowledge from it.
Drywall - A website and user system for Node.js: http://jedireza.github.io/drywall/
I hope this is helpful. Feel free to open issues in GitHub if you run into any road blocks.

Resources