How to get values from mongodb and display in HTML - javascript

I am new to mongodb, I am using Express, Body-Parser and Mongoose and I have a mongodb database (its online, its call mlab) where i pull data from. Every thing is working fine, i have used postman to Get, Post and Delete. I am trying to get the data in JavaScript so i can display in the html. I am using Ajax, it works and returns success, but fires the fail function of the Ajax.
exports.photoalbum_all = function (req, res, next) {
PhotoAlbum.find(({}), function (err, photoalbum) {
if (err) return next(err);
res.send("../Views/images", {photo: photoalbum});
});
};
The mongodb model
const mongoose = require('mongoose');
const Schema = mongoose.Schema,
let PhotoAlbumSchema = new Schema({
title: String,
albums:[
{
u_name: String,
u_title: String
}]
},{
timestamps: true
});
PhotoAlbumSchema.virtual('pictureId').get(function(){
return this._id;
});
The mongodb route
const express = require('express');
const router = express.Router();
//
// Require the controllers
const photoalbum_controller =
require('../controllers/photoalbum.controller');
//
router.get('/find', photoalbum_controller.photoalbum_all);
The app.js
// app.js
const express = require('express');
const bodyParser = require('body-parser');
const photoalbum = require('./routes/photoalbum.route'); // Imports routes for the photos
//
const app = express();
//
// Set up mongoose connection
const mongoose = require('mongoose');
let dev_db_url = 'mongodb://Trex_son:Salvat1on1987#ds243254.mlab.com:43254/photoalbumdb';
let mongoDB = process.env.MONGODB_URI || dev_db_url;
mongoose.connect(mongoDB, { useNewUrlParser: true });
mongoose.Promise = global.Promise;
let db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/photoalbums', photoalbum);
let port = 1234;
app.listen(port, () => {
console.log('Server is up and running on port number ' + port);
});
I'm not sure Ajax is the best way to retrieve this data, is there any better to retrieve this values to the html

Related

How do i get my mongo schema to export into a file then use it to insert data?

I am having trouble being able to insert data into my collection, I'm not even sure I'm doing it correctly so I apologize for the vague request but maybe my code will help you see what my intention is. The gist of it is I'm trying to make a separate file for my schema/collection and then call it from another file and insert data and call other functions etc.
file1.js file:
require('dotenv').config()
const User = require('./assets/js/data')
const bodyParser = require("body-parser");
const mongoose = require('mongoose');
mongoose.connect(process.env.url, { useNewUrlParser: true })
.then(() => {
console.log('Connected to MongoDB server');
})
// 1. Import the express module
const express = require('express');
// 2. Create an instance of the express application
const app = express();
app.set('views', './static/html');
app.set('view engine', 'ejs');
app.use(express.static('assets'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// 3. Define the HTTP request handlers
app.get('/', (req, res) => {
res.render('main')
});
app.get('/login', (req, res) => {
res.render('login')
});
app.post('/login', (req, res) => {
console.log(req.body.number);
})
app.listen(3000, (err) => {
console.log("running server on port")
if (err) {
return console.log(err);
}
})
data.js
const mongoose = require('mongoose');
const userData = new mongoose.Schema({
phoneNumber: String,
})
const User = mongoose.model('User', userData);
module.exports(
User,
)
This line has the error.
// error
module.exports(
User,
)
module.exports is not a function.
module.exports = User
// or
module.exports = { User }
if you do the first one, then required should be like this,
const User = require('./assets/js/data')
otherwise
const { User } = require('./assets/js/data')
More about module.exports
The Data.js is correct but the way your controller works is I think the issue. If you use "const User = require('./assets/js/data')" you can use your selected variable User and then connect find, create, etc. you can use this as a reference. https://blog.logrocket.com/mern-stack-tutorial/

How do i display my data from MongoDB Atlas in my node js application?

I am trying to display data from sample collection thats in mongoDB Atlas. i have connected to the server, retrieved the data. But the problem is i cannot choose specific data. if i do it says undefined.
Here is the pic and code for better understanding:
MY MOVIE MODEL movie.js
const mongoose = require("mongoose");
const { Schema } = mongoose;
require("dotenv").config();
const mongoDB_API = process.env.MONGODB_API_KEY;
const mflixDB = mongoose.createConnection(mongoDB_API).useDb("sample_mflix");
const Movies = mflixDB.model("Movie", new Schema({}), "movies");
module.exports = Movies;
I used the code via mongoose access preexisting collection
Snippet of MongoDB ATLAS:
my app.js
const express = require('express');
const bodyParser = require('body-parser');
const _ =require('lodash');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
app.set("view engine","ejs");
app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static('public'));
const Movies = require('./model/mflix/movies');
app.get("/movies",async (req, res) => {
const ourMovies = await Movies.find().sort({'date': -1}).limit(2);
console.log("WE recieved: \n")
console.log(ourMovies);
const titles =[];
ourMovies.forEach( x=>{
console.log(x._id, x.title)
})
res.render("movies", { recievedList: ourMovies });
});
the output:
As u can see x.title is undefined instead of respective title.
I cannot access any info other than _id.
Is this because i didn't properly defined my schema for the model ?
How do i fix this?
I was browsing more on this answer(this link) and decided to try other ways to do similar thing
Solution from this: Solution, i tried that soliton and added it in my code in following manner:
in app.js
const express = require('express');
const bodyParser = require('body-parser');
const _ =require('lodash');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
app.set("view engine","ejs");
app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static('public'));
//we dont really need this (UNUSED)
const Movies = require('./model/mflix/movies');
const mongoDB_API = process.env.MONGODB_API_KEY;
const mflixDB = mongoose.createConnection(mongoDB_API).useDb("sample_mflix");
app.get("/movies", async (req, res) => {
const collection = mflixDB.collection("movies");
collection
.find({})
.limit(2)
.toArray(function (err, data) {
console.log("\nour data:");
console.log(data); // it will print your collection data
data.forEach(x=>{
console.log(`Id: ${x._id} \t title: ${x.title}`)
})
});
const ourMovies = await Movies.find().sort({ date: -1 }).limit(2);
// console.log("WE recieved: \n")
// console.log(ourMovies);
// const titles =[];
// ourMovies.forEach( x=>{
// console.log(x._id, x.title)
// })
res.render("movies", { recievedList: ourMovies });
});
The output:It shows title (and not undefined like above question)

Receiving a Cannot POST error when attempting to post data in a rest client

I am receiving this error when attempting to post a new entry into a database I have created, called Doctors.
My server.js looks like this:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
const router = express.Router();
const MongoClient = require('mongodb').MongoClient;
const client = new MongoClient(uri, { useNewUrlParser: true });
const morgan = require('morgan');
var Doctor = require('./www/js/user.js');
app.use(bodyParser.json());
app.use(express.static('www'));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ 'extended': 'true' }));
app.use(bodyParser.json());
const mongoURL = 'mongodb://localhost:27017/app';
mongoose.connect(mongoURL, function (err) {
if (err) {
console.log('Not connected to the database:' + err);
} else {
console.log('Successfully connected to MongoDB');
}
});
app.post('/doctors', function (req, res) {
var doctor = new Doctor();
doctor.doctorID = req.body.doctorID;
doctor.password = req.body.password;
doctor.save();
res.send('doctor created');
});
// Configure port
const port = process.env.PORT || 8080;
// Listen to port
app.listen(port);
console.log(`Server is running on port: ${port}`);
app.get('*', function (req, res) {
res.sendfile('./www/index.html');
});
My user.js, which is my schema, looks like this:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');
var DoctorSchema = new Schema({
doctorID: {type: Number, required: true, unique: true},
password: {type: String, required: true}
});
//encrypt password
DoctorSchema.pre('save', function(next){
var doctor = this;
bcrypt.hash(doctor.password, null, null, function(err, hash){
if (err) return next(err);
doctor.password = hash;
next();
});
})
module.exports = mongoose.model('Doctor', DoctorSchema);
When attempting to post, I get this error.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /doctors</pre>
</body>
</html>
I don't understand why I'm getting this particular error. I can get data from /doctors with no issues, I just can't post to it.
Please change your server.js to this:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
const MongoClient = require('mongodb').MongoClient;
const client = new MongoClient(uri, { useNewUrlParser: true });
const morgan = require('morgan');
var Doctor = require('./www/js/user.js');
app.use(bodyParser.json());
app.use(express.static('www'));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ 'extended': 'true' }));
app.use(bodyParser.json());
const mongoURL = 'mongodb://localhost:27017/app';
mongoose.connect(mongoURL, function (err) {
if (err) {
console.log('Not connected to the database:' + err);
} else {
console.log('Successfully connected to MongoDB');
}
});
app.post('/doctors', function (req, res) {
var doctor = new Doctor();
doctor.doctorID = req.body.doctorID;
doctor.password = req.body.password;
doctor.save();
res.send('doctor created');
});
// Configure port
const port = process.env.PORT || 8080;
app.get('*', function (req, res) {
res.sendfile('./www/index.html');
});
app.listen(port, function() {
console.log(
`Server listening on port ${port}!`
);
});
EDIT - Just correcting an issue in the .listen
Cannot POST /doctors in express means that a particular route doesn't exist.
Can you show more code, on what port are you posting ?
Did you set the right content type in the request?
Content-Type: application/json
Else, the req.body.doctorID will return undefined.
I just tested this successfully.. It appears the issue is with your Mongo code..
Try this, if it works, you know the issue is with the Mongo section.
This is how I am sending the requests.. using Postman
This shows how I am able to receive the request:
const express = require('express');
const bodyParser = require('body-parser');
//const mongoose = require('mongoose');
const app = express();
const router = express.Router();
//const MongoClient = require('mongodb').MongoClient;
//const client = new MongoClient(uri, { useNewUrlParser: true });
//const morgan = require('morgan');
//var Doctor = require('./www/js/user.js');
app.use(bodyParser.json());
app.use(express.static('www'));
//app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ 'extended': 'true' }));
app.use(bodyParser.json());
//const mongoURL = 'mongodb://localhost:27017/app';
/*
mongoose.connect(mongoURL, function (err) {
if (err) {
console.log('Not connected to the database:' + err);
} else {
console.log('Successfully connected to MongoDB');
}
});
*/
app.post('/doctors', function (req, res) {
console.log(req.body);
res.status(200).send();
/*
var doctor = new Doctor();
doctor.doctorID = req.body.doctorID;
doctor.password = req.body.password;
doctor.save();
res.send('doctor created');
*/
});
// Configure port
const port = process.env.PORT || 8080;
// Listen to port
app.listen(port);
console.log(`Server is running on port: ${port}`);
app.get('*', function (req, res) {
res.sendfile('./www/index.html');
});
To expand on this answer.. I usually configure Mongoose in the following manner..
Folder Structure:
root
|- database
|- index.js
|- models
|- someModel.js
In /root/database/index.js:
'use strict'
const mongoose = require('mongoose');
const mongoBaseUrl = `mongodb://server:27017/collection`;
const mongoDB = mongoose.createConnection(mongoBaseUrl, { useNewUrlParser: true, promiseLibrary: global.Promise });
mongoose.set('useCreateIndex', true) // needed to suppress errors
module.exports = mongoDB;
Then in /root/models/someModel.js:
'use strict'
const mongoose = require('mongoose');
const mongoConnection = require('../database');
const modelName = "SomeModel";
const collection = "SomeCollection";
const databaseName = "SomeDatabase";
const myDatabase = mongoConnection.useDb(databaseName);
const SomeSchema = new mongoose.Schema({
// Schema data here
})
module.exports = myDatabase.model(modelName, SomeSchema, collection) // (database, schema, collection)
Then to use it in your routes:
const Doctor = require('./models/someModel.js');
app.post('/route/', (req, res, next) => {
var doctor = new Doctor();
doctor.doctorID = req.body.doctorID;
doctor.password = req.body.password;
doctor.save();
res.send('doctor created');
});
Something to that effect. Hope this helps.
It turns out the issue was with neither, we had a duplicated server.js, and it was referencing the incorrect one. Thanks for the help anyway! Hope this thread helps someone else.

How to query imported json using Mongoose

I've uploaded a json file to MongoDB Atlas cluster (using mongoimport) and now I'm trying to display the data to localhost using express and mongoose.
I've gotten to a point where I can connect to the cluster but I'm struggling in fetching and displaying the data. Below is the code I have thus far. I'd like to query the database via Nodejs using mongoose as I do on the command line with Mongo shell. What am I missing here?
const express = require("express");
const mongoose = require("mongoose");
const app = express();
// DB config using Mongo Atlas
const uri = require("./config/keys").mongoURI;
// // Connect to Mongo
mongoose
.connect(uri, { useNewUrlParser: true })
.then(() => console.log("MongoDB Connected..."))
.catch(err => console.log(err));
// #route GET
app.get("/", (req, res) => res.send(db.restaurants.find()));
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
First, initialize a model which Mongoose needs to query data. Since you've imported the data, you don't necessarily have to structure your schema.
// restaurants.js
const mongoose = require('mongoose');
const RestaurantsSchema = new mongoose.Schema({});
module.exports = mongoose.model('Restaurants', RestaurantsSchema)
Then, import the schema 'Restaurants' into your main driver file and specify your query by chaining filters like so:
// main.js
const express = require("express");
const mongoose = require("mongoose");
const Restaurants = require("./restaurants");
const app = express();
// DB config using Mongo Atlas
const uri = require("./config/keys").mongoURI;
// Connect to Mongo
mongoose
.connect(uri, { useNewUrlParser: true })
.then(() => console.log("MongoDB Connected..."))
.catch(err => console.log(err));
// #route GET
app.get("/", (req, res) => {
Restaurants.find()
.where("filter1").gt(200)
.where("filter2").equals("$$$")
.where("filter3").nin(["Coffee"])
.limit(100)
.sort("sort1")
.select("column1 column2 column3")
.then(restaurants => res.json(restaurants))
.catch(err => res.status(404).json({ success: false }));
});
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
You should fill in the applicable values for "filter", "sort", "column", "gt", "equals", "limit", and "nin".
I am not sure if this is the only record of that type of json in your data base. But If you want to send if follwing a get request you first need to get the document.
// #route GET
app.get("/", (req, res) => res.send(db.restaurants.find()));
// may be something like
app.get('/', (req, res) => {
mongooseModel.find({query}, (err, result) => {
res.send(result);
});
})
Depending on what mongoose.model defenition you have and how you would like to find it you could use find (return an array) findById (return single document) or findOne and a query.
here an example how to create you model:
//restaurant.js
const mongoose = require('mongoose');
const RestaurantSchema = new mongoose.Schema({
name: { type: String, required: true },
address: { type: String, required: true },
description:{ type: String, required: true }
//just you add how you need your schema
});
module.exports = mongoose.model('Restaurant', RestaurantSchema);
and here your updated code
const express = require("express");
const mongoose = require("mongoose");
const Restaurant = require("./restaurant.js");
const app = express();
// DB config using Mongo Atlas
const uri = require("./config/keys").mongoURI;
// // Connect to Mongo
mongoose
.connect(uri, { useNewUrlParser: true })
.then(() => console.log("MongoDB Connected..."))
.catch(err => console.log(err));
// #route GET
app.get("/", (req, res) => {
Restaurant.find({}, (err, docs) => {
res.send(docs);
});
);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));

Can not establish mongodb connection from node js

I made this node js app and then i tried with postman but every time i made a request that involves mongodb, it keeps loading. The function find of the model is where the code stops and the callback is never called.
app.js
var express = require("express"),
app = express(),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
mongoose = require('mongoose');
//Connection to DB
mongoose.connect('mongodb://localhost:27017/users', function(err, res) {
if(err) {
console.log('ERROR: connecting to Database. ' + err);
}
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
var models = require('./models/user')(app, mongoose);
var userContoller = require('./controllers/user');
var router = express.Router();
router.get('/', function(req, res) {
console.log('GET');
res.send("Hello World!");
});
app.use(router);
var users = express.Router();
users.route('/users')
.get(userContoller.findAllUsers);
app.use('/api', users);
app.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});
models/user.js
exports = module.exports = function(app, mongoose){
var userSchema = new mongoose.Schema({
userName: { type: String },
password: { type: Number }
});
mongoose.model('User', userSchema);
};
controllers/user.js
var mongoose = require('mongoose');
var User = mongoose.model('User');
//GET - Return all tvshows in the DB
exports.findAllUsers = function(req, res) {
console.log('llega');
User.find(function(err, users) {
if(err) res.send(500, err.message);
console.log('GET /users')
res.status(200).jsonp(users);
});
};
The mongodb server is started through the console but i don't know how to check it.
Thanks!
EDIT:
I made the code easier for me to test and solve the problem.
The code now is this and im not getting the connection to mongodb.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', function() {
console.log('error');
});
db.once('open', function() {
console.log('connected');
});
I don't get in the console the error or the connected.
In the mongod console i get some messages saying that a new connection was made. This happens every time i open the nodejs program.
Thanks
I think the problem is that you are giving call back to the mongoose.connect function. In my case i did:
mongoose.connect(url, options)
const db = mongoose.connection
db.on('error', function () { console.log('Cannot Connect to DB') })
db.once('open', function () { console.log('Mongoose Connected to DB') })
Also instead of:
users.route('/users').get(userContoller.findAllUsers);
You may try:
users.get('/users', userController.findAllUsers);
And I realized that you don't pass a next argument to your controller which express generally complains if you dont pass.
Edit: I think i found the error.
When you are using the .find function you need to pass 2 arguments. In your case because you are not passing the callback as the second argument it never gets called.
User.find({}, callback) should do it.
I found the problem.
The version of mongoose was older than the needed to connect to my mongodb version. Just update it via npm and good to go.

Categories

Resources