MERN stack : Express api returning empty data , but the data is already present in mongodb - mongodb

I am new to the MERN stack, and I have been trying to access my collections in MongoDB.
Here is the code for the router, view bookings:
/*This is router file*/
var mongoose = require('mongoose');
const express = require('express');
const bodyParser = require('body-parser')
let book = require('../models/BookTravel');
const router = require('express').Router()
router.use(express.json())
router.route('/').get((req, res) => {
// Company.aggregate({companyId})
book.find()
.then((result) => {
console.log(result)
return res.status(200).json(result)
})
})
module.exports = router;
/*
* this is for model
*/
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const TravelSchema = new Schema({
firstname:{
type: String,
required: true
},
bookingId:{
type: String,
required: true
},
lastname:{
type: String,
required: true
},
startcity:{
type: String,
required: true
}
})
const travel = mongoose.model('travel', TravelSchema)
module.exports = travel;
////in app.js file
const viewBookings = require('./routes/viewBookings');
app.use('/viewBookings', viewBookings)
The postman is also giving empty result.
What am I missing out ? Is it not possible to access the already existing collection with this method ?

You are missing some code in the router file.
for example! If you want to get data from a database
you can simply use like below this
.......
router.get("/",async (req,res)=>
{
try{
const result = await book.find();
res.status(200).json({"message" : result})
}
catch(error)
{
console.log(error)
}
})
......

Related

Mongoose getters are either not working the way I want or I'm misunderstanding what they are

I created some sample code to demonstrate my issue on a smaller scale. From my understanding, a getter function will not affect anything on my database, but when I want to make a get request to view items on my database, it will change the value to whatever is returned only when the data is displayed. However, when I make my get request to view items on my database, the item I am shown is exactly how it was saved. I'm not sure if I'm misunderstanding what a getter function is, or if my syntax is just incorrect somewhere.
Here is my main server:
const express = require('express')
const mongoose = require('mongoose')
// Linking my model
const User = require('./User')
// Initializing express
const app = express()
const PORT = 9999
app.use(express.json())
// Connecting to mongodb
const connectDB = async () => {
try {
await mongoose.connect('mongodb://localhost/testdatabase', {
useUnifiedTopology: true,
useNewUrlParser: true
})
console.log('Connected')
} catch (error) {
console.log('Failed to connect')
}
}
connectDB()
// Creates a new user
app.post('/user/create', async (req, res) => {
await User.create({
name: 'John Cena',
password: 'somepassword'
})
return res.json('User created')
})
// Allows me to view all my users
app.get('/user/view', async (req, res) => {
const findUser = await User.find()
return res.json(findUser)
})
// Running my server
app.listen(PORT, () => {
console.log(`Listening on localhost:${PORT}...`)
})
Here is my model:
const mongoose = require('mongoose')
// My setter - initialPassword is 'somepassword'
// This seems to work properly, in my database the password is changed to 'everyone has the same password here'
const autoChangePassword = (initialPassword) => {
console.log(initialPassword)
return 'everyone has the same password here'
}
// My getter - changedPassword should be 'everyone has the same password here' I think
// The console.log doesn't even run
const passwordReveal = (changedPassword) => {
console.log(changedPassword)
return 'fakehash1234'
}
// Creating my model
const UserSchema = mongoose.Schema({
name: {
type: String
},
password: {
type: String,
set: autoChangePassword,
get: passwordReveal
}
})
// Exporting my model
const model = mongoose.model('user', UserSchema)
module.exports = model
Not sure if it would help anyone since I found my answer on another StackOverflow post, but the issue was I had to set getters to true when converting back to JSON:
// Creating my model
const UserSchema = mongoose.Schema({
name: {
type: String
},
password: {
type: String,
set: autoChangePassword,
get: passwordReveal
}
}, {
toJSON: { getters: true }
})
Any similar problems can be solved by adding some combination of the following:
{
toJSON: {
getters: true,
setters: true
},
toObject: {
getters: true,
setters: true
}
}

Express Sequelize Error - Cannot read property 'findAll' of undefined

I have successfully connected Sequelize and Express using Sequelize's github example with a few changes. I am now trying to do a simple Sequelize query to test the connection, but continue to receive an error stating that the model I have queried is not defined.
// ./models/index.js
...
const sequelize = new Sequelize(process.env.DB, process.env.DB_USER, process.env.DB_PASS, {
host: 'localhost',
dialect: 'postgres'
});
// Test SEQUELIZE connection
sequelize
.authenticate()
.then(() => {
console.log('Database connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
// ./routes/index.js
const models = require('../models');
const express = require('express');
const router = express.Router();
router.get('/contacts', (req, res) => {
models.Contact.findAll().then(contacts => {
console.log("All users:", JSON.stringify(contacts, null, 4));
});
});
module.exports = router;
// ./models/contact.js
const Sequelize = require('sequelize');
var Model = Sequelize.Model;
module.exports = (sequelize, DataTypes) => {
class Contact extends Model {}
Contact.init({
// attributes
firstName: {
type: Sequelize.STRING,
allowNull: false
},
lastName: {
type: Sequelize.STRING,
allowNull: false
}
}, {
sequelize,
modelName: 'contact'
// options
});
return Contact;
};
The error I am getting when using postman to hit /contacts with a GET request is:
[nodemon] starting `node server.js`
The server is now running on port 3000!
Executing (default): SELECT 1+1 AS result
Database connection has been established successfully.
TypeError: Cannot read property 'findAll' of undefined
at router.get (C:\Users\username\desktop\metropolis\metropolis-backend\routes\index.js:6:20)
You are not requiring the model properly.
In ./routes/index.js add the next line:
const Contact = require('./models/contact.js');
And then call Contact.findAll()...
Second approach:
You can gather all your models by importing them into a loader.js file which you will store in the models directory. The whole job of this module is to import the modules together to the same place and then export them from a single place.
It will look something like that:
// loader.js
const modelA = require('./modelA');
const modelB = require('./modelB');
const modelC = require('./modelC');
...
module.exports = {
modelA,
modelB,
modelC,
...
}
And then you can require it in the following way:
in router/index.js:
const Models = require('./models');
const contact = Models.Contact;

mongoose not fetching data

I am trying to fetch all users from a MongoDB database. However for some reason recently the request did not fetch anything.
Here is the code in which I try to fetch the data:
app.get('/api/allusers', (req, res) => {
Employee.find()
.then(rettrievedData => {
res.json(rettrievedData)
});
});
Here is the mongoose model:
const mongoose = require('mongoose');
const employeeSchema = mongoose.Schema({
name: { type: String },
surName: { type: String },
mail: { type: String },
phone: { type: String },
});
module.exports = mongoose.model('Employee', employeeSchema, 'employee.employees');
Here is the code for connecting to Mongo
mongoose.connect("mongodb+srv://Kiril:xxxxxxxxxxxxx#cluster0-owdfy.mongodb.net/employee?retryWrites=true&w=majority")
.then(() => {
console.log("Connected")
})
Also I have checked that there is data in the database, but for some reason the Employee.find() does not retrieve anything. What can be reason?
Thanks in advance.
why you are adding 'employee.employyes' when you creating your model
try to export the model without it
module.exports = mongoose.model('Employee', employeeSchema)
or better
exports.Employee = mongoose.model('Employee', employeeSchema)
and require it where you want to use it
const Employee = require('path to the schema file')

MissingSchemaError: Schema hasn't been registered for model "Blog"

I am getting above error which I am stuck I am a beginner of mongodb, expressjs
My Index.js:
const mongoose= require('mongoose')
let modelspath ='./models'
fs.readdirSync(modelspath).forEach(function(file){
if(~file.indexOf('.js'))
console.log(file)
require(modelspath +'/' + file) //if block checks weather file ending with .js ext
})
my controller file
const BlogModel = mongoose.model('Blog')
let testRoute = (req, res) =>
{
console.log(req.params)
res.send(req.params)
}
my model.blog.js file
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
let blogSchema =new Schema(
{
blogId :{
type: string,
unique:true
},
mongoose.model('Blog',blogSchema);
my routing file
const express =require('express')
//here we can find routees logic path
const control =require('./../controllers/controller')
let setRouter =(app) =>{
//here we are getting our logics and assigning for a Http verbs (get,post,put,del)
app.get('/test/route/:param1/:param2',control.testRoute)
app.get('/example',control.example)
// app.post('/hello', control.postmethod)
}
module.exports={
setRouter:setRouter
}
Can anyone help me out of this error

connect apollo server with mongodb mongoos

I'm trying to connect apollo-server with my mongodb on mlab (I tried with my local mongo as well). I can connect to the db fine, although nothing is returned when testing with a graphql query. I just can't figure out how to actually get the data back from the db. I am using the latest apollo-server-express.
I've put this together from various tutorials and the docs but can't find a clear answer on my problem. Probably missing something very obvious.
Server.js
import express from 'express';
import { ApolloServer, gql } from 'apollo-server-express';
import Mongoose from 'mongoose';
import { Post } from './models/Post';
const app = express();
Mongoose.Promise = global.Promise;
Mongoose.connect('mongodb://<username>:<pw>#ds151282.mlab.com:51282/groupin', { useNewUrlParser: true })
.then(()=> console.log('DB connected'))
.catch(error => console.log(error))
const typeDefs = gql`
type Post {
title: String
description: String
author: String
url: String
}
type Query {
allPosts: [Post]
}
`;
const resolvers = {
Query: {
allPosts(parent, args) {
return Post.find({})
}
}
};
const apollo = new ApolloServer({
typeDefs,
resolvers,
context: ({req}) => ({ Post })
});
apollo.applyMiddleware({ app })
app.listen(4000, () => {
console.log(`🚀 Server ready at http://localhost:4000${apollo.graphqlPath}`);
});
Post.js
import Mongoose from 'mongoose';
const PostSchema = {
title: String,
description: String,
author: String,
url: String
};
const Post = Mongoose.model('Post', PostSchema);
export { Post };
Try to use mongoose Schema instead of plain object
Post.js
import Mongoose from 'mongoose';
const PostSchema = new Mongoose.Schema({
title: String,
description: String,
author: String,
url: String
});
const Post = Mongoose.model('Post', PostSchema);
export { Post };