mongoose not fetching data - mongodb

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')

Related

MERN stack : Express api returning empty data , but the data is already present in 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)
}
})
......

Is there a way to convert a date value to a User's timezone in Mongoose?

I have searched everywhere, StackOverflow and else where but I can't seem to find a fix for my problem. I have a mongoose schema like this:
// user.model.js
const mongoose = require('mongoose');
const User = new Schema({
firstName: String,
lastName: String,
tz: String,
registrationDate: {
type: Date,
default: Date.now(),
}
})
And I have a controller which creates a User like this:
// user.controller.js (async)
let user = await User.create({
'firstName': 'John',
'lastName': 'Doe',
'tz': 'Africa/Kampala'
});
await reply.send(user); // I am using Fastify framework
No matter what I do, when the User is returned it always gives the UTC time and not the time that the User actually is in. have tried using Mongoose transform:
// Transform on the schema
const moment = require('moment-timezone');
const User = new Schema({
// Schema definitions
}, {
toJSON: {
transform: function (doc, ret) {
ret.registrationDate= moment.tz(doc.registrationDate, doc.tz).format();
return ret;
}
}
})
And have also tried using get like this:
const User = new Schema({
// Other definitions
registrationDate: {
type: Date,
default: Date.now(),
get: convertDate
}
})
function convertDate(registrationDate) {
return moment.tz(registrationDate, this.tz).format()
}
But no luck. I would appreciate any assistance or guidance in getting this to work on the model. Thanks!

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
}
}

Can't save to mongoDB's database

While sending a post request i written the following code :
var email = req.body.email ;
var newDetails = { email: email };
Details.create(newDetails);
console.log(newDetails);
while sending the request. The console.log shows me the correct details,
However in the mongo shell the only collection that exist is "details" and it's empty .
That's the Mongoose Schema:
var mongoose = require("mongoose");
var DetailsSchema = mongoose.Schema({
email: String
});
module.exports = mongoose.model("Details", DetailsSchema);
I'm using NodeJS.
Thanks in advance.
Your Mongoose Model should be like
const mongoose = require("mongoose");
const Scheme = mongoose.Schema;
const DetailsSchema = new Scheme({
email: String
});
module.exports = mongoose.model("Details", DetailsSchema);
Node js Code should be like
var detailsModel = require('../model/Details.js');//path of mongoose model
var detailsData = new detailsModel();
detailsData.email = req.body.email;
detailsData.save(function (err, savedJob) {
if (err) {
return res.send(err);
} else {
return res.send(savedJob);
}
});
To save data in mongoDB's Database
You can use this way
var detailsData = new detailsModel();
detailsData.save()
.then(business => {
res.status(200).json({'Details': 'newDetails added successfully'});
})
.catch(err => {
res.status(400).send("unable to save to database");
});
With this, you can also handle error easily.

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 };