I'm trying to retrieve data from my mongo database. The problem occurs when I try to do the get route in my API. The error I get is: SchemeName.collection is not a function.
Here is my API in routes/api/tejidos
const express = require("express");
const router = express.Router();
const Equipo = require("../../../models/Equipo");
router.post("/crear", (req, res) => {
// Form validation
const newEquipo = new Equipo({
nombre: req.body.nombre,
marca: req.body.marca,
modelo: req.body.modelo,
serial: req.body.serial,
proveedor: req.body.proveedor,
estado: req.body.estado,
zona: req.body.zona,
fechaCompra: req.body.fechaCompra,
tiempoGarantia: req.body.tiempoGarantia,
guiaUsoRapido:req.body.guiaUsoRapido
});
//if (err) throw err
newEquipo
.save()
.then(equipo=>res.json(equipo))
.catch(err => console.log(err));
});
router.get('/leer', function(req, res) {
const equipos = Equipo.collection("equipos")
res.json({
equipos: equipos
});
});
module.exports = router;
And this is my server.js
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const users = require("./routes/api/users");
const equipos = require("./routes/api/tejidos/equipos");
const app = express();
// Bodyparser middleware
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
// DB Config
const db = require("./config/keys").mongoURI;
// Connect to MongoDB
mongoose
.connect(
db,
{ useNewUrlParser: true }
)
.then(() => console.log("MongoDB successfully connected"))
.catch(err => console.log(err));
// Passport middleware
app.use(passport.initialize());
// Passport config
require("./config/passport")(passport);
// Routes
app.use("/api/users", users);
app.use("/api/tejidos/equipos", equipos);
const port = process.env.PORT || 5000; // process.env.port is Heroku's port if you choose to deploy the app there
app.listen(port, () => console.log(`Server up and running... ${port} !`));
I need to retrieve data in my collection (the ones I created with the post method) from the database when I use the GET method in Postman at http://localhost:5000/api/tejidos/equipos/leer
Also, I will appreciate any documentation that you recommend.
Simply use find method:
router.get('/leer', async (req, res) => {
const equipos = await Equipo.find();
res.json({ equipos });
});
And here is the helpful documentation for making queries with mongoose
Related
This is an express server that interacts with a mongoDb server using mongoose.Here I want to search for a specific entry with a given name instead of using findbyid function in the /getCollege/:name route.
const express = require('express');
const College = require('./model/collegeModel')
const parser = require('body-parser');
const app = express();
const mongoose = require('mongoose');
const collegeData = require('./data/college_data.json')
// app.use(parser);
mongoose.connect('mongodb+srv://swapnil:abc#cluster0.ma46p.mongodb.net/db?retryWrites=true&w=majority', { useNewUrlParser: true, useUnifiedTopology: true }).then(() => { console.log('connected to db') })
//
app.get('/', (req, res) => {
res.send('We are home');
})
app.get('/getCollege/:name',async (req,res) =>{
})
app.listen(3000);
Parameters variables such as :name are available through req.params, on your case: req.params.name. After getting the value you would something like:
const express = require('express');
const College = require('./model/collegeModel')
const parser = require('body-parser');
const app = express();
const mongoose = require('mongoose');
const collegeData = require('./data/college_data.json')
// your code
app.get('/getCollege/:name',async (req, res) =>{
try {
const document = await College.findOne({ name: req.params.name });
res.json(document);
} catch(error) {
// Handle the error here.
console.log(error);
}
});
// your code
Take a look at these reading materials as well:
1 - http://expressjs.com/en/guide/routing.html
2 - https://medium.com/weekly-webtips/9-best-practices-for-rest-api-design-7fb0b462099b
Anyone can help me I am new to node js and I am stuck with this error it return 404 not found when I am trying to visit http://localhost:5000/api/items on my postman..
this is the file items.js
const express = require('express');
const router = express.Router();
//Items Model
const Item = require('../../models/Item');
router.get('/', (req, res) => {
Item.find()
.sort({date: -1})
.then(items => res.json(items))
});
router.post('/', (req, res) => {
const newItem = new Item({
name: req.body.name
});
newItem.save().then(item => res.json(item));
});
module.exports = router;
this is the server.js file
const express = require('express');
const mongoose = require('mongoose');
const app = express();
app.use(express.json());
const items = require('./routes/api/items');
const db = require('./config/keys').mongoURI;
mongoose.connect(db, {useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true })
.then(() => console.log('connected to mongo'))
.catch(err => console.log(err));
app.use('api/items', items);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`port started ${port}`));
add a '/' before pathname in server.js
app.use('/api/items', items);
localhost:5000/api/items should work then
You need to make the following changes to your server.js
import your router module
const express = require('express');
const mongoose = require('mongoose');
const router = require('path of the router module');
const app = express();
app.use(express.json());
app.use(router); //to use your router
const items = require('./routes/api/items');
const db = require('./config/keys').mongoURI;
mongoose.connect(db, {useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true })
.then(() => console.log('connected to mongo'))
.catch(err => console.log(err));
app.use('/api/items', items);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`port started ${port}`));
Try this:-
As I can see in the image of "vscode"
you have used router.get("/")
whereas in postman you are using URL for GET request as localhost:5000/api/items.
Either change your backend code to router.get("/api/items") or correct your postman request to localhost:5000/
I am learning a MERN stack course on Udemy and currently I am trying to retrieve the user's data from the server but I can't. I am able to retrieve the post data but the connections times out for users data. Can you guys help me find out what went wrong? Thank you in advance!
userController snippet:
exports.allUsers = (req, res) => {
const users = User.find({})
.then((users) => {
console.log(users);
})
.catch(err => console.log(err));
};
User routes snippet
const express = require('express'),
router = express.Router(),
{userById, allUsers } = require('../controllers/userController');
router.get('/users', allUsers);
router.param('userID', userById)
module.exports = router;
app.js code snippet
const express = require('express'),
app = express(),
postRoutes = require('./routes/post'),
authRoutes = require('./routes/auth'),
morgan = require("morgan"),
mongoose = require("mongoose"),
bodyParser = require("body-parser"),
cookieParser = require('cookie-parser'),
userRoutes = require('./routes/user'),
expressValidator = require('express-validator');
require('dotenv').config();
mongoose.connect(process.env.MONGO_URI,
{ useUnifiedTopology: true, useNewUrlParser: true })
.then(() => console.log("DB connected"));
app.use(morgan("dev"));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(expressValidator());
app.use('/', postRoutes);
app.use('/', authRoutes);
app.use('/', userRoutes);
app.use(function (err, req, res, next) {
if (err.name === 'UnauthorizedError') {
res.status(401).json({error: "Unauthorised"});
}
});
app.listen(process.env.PORT || 3000, () => {
console.log(`SERVER AT PORT: 3000`);
});
Postman gets stuck here:
You have to end the request / respond to the request . In your userController you are missing ending/responding the request. You are just logging the user result .
Try this :
exports.allUsers = (req, res) => {
const users = User.find({})
.then((users) => {
console.log(users);
res.status(200).json(users);
})
.catch((err) => {
console.log(err);
res.status(500).json(err.message);
});
}
I m testing a simple Get api with postman, but i am getting "cannot GET".
server.js (in the root folder)
```const express = require('express');
const mongoose = require('mongoose');
const items = require('./routes/api/items');
const app = express();
//body Parser middleware
app.use(express.json());
//Db config
const db = require('./config/keys').mongoURI;
//const db = "mongodb+srv://gkmm:123123123#cluster0-bo4ln.mongodb.net/test?retryWrites=true&w=majority"
//Connect to mongo
mongoose
.connect(db, { useNewUrlParser:true, useUnifiedTopology: true})
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
const port = process.env.PORT || 4000;
app.listen(port, () => console.log(`Server started on port ${port}`));
//Use routes
app.use('./routes/api/items.js', items);```
routes(root folder)/api/items.js
```const express = require('express')
const router = express.Router();
//Item Model
const Item = require('../../models/Item')
//#route GET api/items
//#des Get AAll Items
//access public
router.get('/', (req, res) => {
Item.find()
.sort({ date: -1})
.then(items => res.json(items));
});
module.exports = router; ```
Running into this error while trying to test my API, i checked my paths are correct, my database is connected. but i have no idea why is it returning 404 not found.
After looking through your code, # the line which you ask app to use your routes
//Use routes
/* You are telling the route to go through e.g. <yoururl>/./routes/api/items.js/
in order to reach your GET in items.js
*/
app.use('./routes/api/items.js', items);```
To resolve this issue you can edit your app.use to
app.use('/test', items) // test is just an example, you can change it to other keywords
Then to access your items GET route use "/test/"
Shouldn't app.use('./routes/api/items.js', items); be app.use('/api/items', items); ?
I am wondering if anyone could help me please.
I have a react app that contains dialogflow (google's chatbot platform). I would like to share information in a user route to a dialogflow fulfillmentRoute using express-session. Here is my main server.js file. In the server.js I have declared an express-session
server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const passport = require('passport');
const path = require('path');
var cors = require('cors')
const users = require('./routes/api/users');
const db = require('./config/keys').mongoURI;
require('./models/Users');
const app = express();
const session = require('express-session')
// Body parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());
require('./routes/fulfillmentRoutes')(app);
app.use(session({secret: 'ssshhhhh'}));
// Connect to MongoDB
mongoose
.connect(db)
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
// Passport middleware
app.use(passport.initialize());
// Passport Config
require('./config/passport')(passport);
// Use Routes
app.use('/api/users', users);
// Server static assets if in production
if (process.env.NODE_ENV === 'production') {
// Set static folder
app.use(express.static('client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port ${port}`));
In the user.js route file, I then have this to save an email into a session variable;
user.js
router.post(
'/',
passport.authenticate('jwt', { session: false }),
(req, res) => {
sess = req.session;
var emails = req.user.email;
sess.emails;
res.json({ msg: 'Users Works' })
res.json({
id: req.user.id,
firstname: req.user.firstname,
lastname: req.user.lastname,
email: req.user.email,
week: req.user.week,
age: req.user.age
});
}
);
In my dialogflow fullfillment route file, I have the following;
fulfillmentRoutes.js
const {WebhookClient, Payload, Card} = require('dialogflow-fulfillment');
const express = require('express');
const chatbot = require('../chatbot/chatbot');
const mongoose = require('mongoose');
const passport = require('passport');
const keys = require('../config/keys');
const sourceFile = require('./api/users.js');
const User = require('../models/User');
module.exports = app => {
var router = express.Router();
app.post('/api/df_text_query', async (req, res) => {
let responses = await chatbot.textQuery(req.body.text, req.body.userID, req.body.parameters);
res.send(responses[0].queryResult);
});
app.post('/api/df_event_query', async (req, res) => {
let responses = await chatbot.eventQuery(req.body.event, req.body.userID, req.body.parameters);
res.send(responses[0].queryResult);
});
app.post('/', async (req, res) => {
const agent = new WebhookClient({ request: req, response: res });
async function welcome(agent) {
let user = await User.findOne({'email': sess.emails});
if (user !== null ) {
responseText = `${sess.emails}`;
}
agent.add(responseText);
}
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
agent.handleRequest(intentMap);
});
return router;
}
In the welcome async function in fulfillment.js route, I use sess.emails that was declared in the user.js routes file. However the variable comes back undefined. Any guidance or help will be appreciated please.
Thanks
In your user.js, sess.emails; is not being assigned any variable.
Can you try replacing it sess.emails = emails; and check if the emails field is undefined?