Express rest api and mongoDB lowercase query - javascript

I've created simple Express.js Rest API with MongoDB. I am using this package: https://www.npmjs.com/package/api-query-params and everything works very well except for one thing. I have a URL like this:
localhost/properties/?town=LONDON
this returns all properties from London, the problem is with this is the next thing, I need to put capitalize value (LONDON), I am trying to achieve that this value can be lowercase (london), so final URL will be like this:
localhost/properties/?town=london
My route:
const express = require('express');
const router = express.Router();
const Property = require('../models/Property');
const aqp = require ('api-query-params');
router.get('/all', (req, res, next) => {
const { filter, skip, limit, sort, projection, population, casters } = aqp(req.query, {
casters: {
lowercase: val => req.query.toLowerCase(),
},
});
Property.find(filter)
.skip(skip)
.limit(limit)
.sort(sort)
.select(projection)
.populate(population)
.exec((err, properties) => {
if (err) {
return next(err);
}
res.send(properties);
});
});
module.exports = router;
And app.js
const express = require('express');
const app = express();
const bodyParser = require("body-parser");
require('dotenv/config');
const mongoose = require('mongoose');
const propertyRoute = require('./routes/property');
const PORT = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/properties', propertyRoute);
//routes
app.get('/', (req, res) => {
res.send('value');
});
mongoose.connect('linkdatabse', {
newUrlParser: true,
})
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});
I've updated my route according to documentation: https://www.npmjs.com/package/api-query-params#add-custom-casting-functions
but still, this doesn't work
Can anybody try to help me with this, what am I doing wrong?

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 to solve/fix this issue throw new TypeError('app.use() requires a middleware function') when starts the server in node js

I am facing this issue when trying to run server after create route and use route in app.js file.Please help me to resolve the error i have been stuck here for hours tried a lot of edits but its not working for me.
Here is my courseRoute.js
const express = require('express');
const router = express.Router();
const Course = require('../../models/Course');
const adminAuthMiddleware = require('../../middleware/adminAuthMiddleware');
router.get('/admin/view-course', adminAuthMiddleware, async (req, res) => {
try {
await Course.find((err, docs) => {
if (!err) {
res.render('admin-views/course/view_course', { courses: docs });
} else {
res.send('Error in retrieving Course list :' + err);
}
})
} catch (err) {
res.send(err);
}
});
This is my app.js
require('dotenv').config();
const express = require('express');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const flash = require('connect-flash');
const bodyParser = require('body-parser');
const { check, validationResult } = require('express-validator');
const path = require('path');
require('./db/conn');
const courseRoute = require('./routes/admin routes/courseRoute');
const app = express();
const port = process.env.PORT || 3000;
const static_path = path.join(__dirname, "../public");
app.use(express.static(static_path));
app.use(express.json());
app.use(express.urlencoded({extended: false }));
app.set('view engine', 'ejs');
app.use(courseRoute);
app.listen(port, () => {
console.log(`Server is running at ${port}`);
});
Your courseRoute.js has no exports. In the last line add module.export = route;

Assistance On CRUD Operations For Express App

I don't have much experience and I'm trying to create a simple note taking application where I can use CRUD. I've gotten as far as being able to create a note but I'm stuck on what to actually put for Delete/Put.
Code Below
My app.js file:
const express = require('express');
const mongoose = require('mongoose');
const methodOverride = require("method-override")
const app = express();
const Note = require('./models/note');
const notesRouter = require('./routes/notes');
require('dotenv').config();
app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: false }));
app.use(methodOverride('_method'));
app.get('/', async (req, res) => {
const notes = await Note.find().sort('-createdAt');
res.render('index', { notes: notes });
});
mongoose.connect('mongodb://localhost/notes', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
app.use('/', notesRouter);
app.listen(process.env.PORT || 8080, () => {
console.log(`Server Has Started`);
});
My notes.js file:
const express = require('express');
const router = express.Router();
const Note = require('../models/note');
router.get('/new', (req, res) => {
res.render('new');
});
router.post('/', async (req, res) => {
let note = await new Note({
title: req.body.title,
description: req.body.description,
});
try {
note = await note.save();
res.redirect('/');
} catch (e) {
console.log(e);
res.render('new');
}
});
module.exports = router;
I can't seem to find the correct code to put in so that I can actually delete or update an existing note.
I would appreciate any information and assistance.
delete operation -
router.route('/delete/:id')
.delete((req, res)=>{
const {id}=req.params;
Note.findOneAndDelete({_id:id})
.then(()=>res.send('deleted!'))
.catch(err=>res.send(err))
})
Set your own route if required, from frontend send id or something else by which you can find the document in the database, and use/replace accordingly to complete the operation.
For update a note- use put
router.route('/update/:id')
.put((req, res)=>{
const {id}=req.params;
const {updateField1, updateField2, updateField3}=req.body;
Note.findOneAndUpdate({_id:id}, {$set:{updateField1, updateField2, updateField3}})
.then(()=>res.send('Note updated!'))
.catch(err=>res.send(err))
})

Router not firing .find or .findByID in express app. Using nextjs as well

I am using a NextJS/MERN stack. My NextJS is using my server.js file, along with importing the routes for my API. The routes appear to be working as they do show activity when firing an API call from Postman or the browser. However, this is where the activity stops. It's not getting passed the Model.find() function as far as I can tell. I am not sure if this has to do with Next js and the prepare method in the server.js, or if this is related to the bodyparser issue.
Here is my server.js
const express = require("express");
const urlObject = require('./baseURL')
const passport = require("./nextexpress/config/passport-setup");
const passportSetup = require("./nextexpress/config/passport-setup");
const session = require("express-session");
const authRoutes = require("./nextexpress/routes/auth-routes");
const KBRoutes = require("./nextexpress/routes/kb-routes");
const userRoutes = require('./nextexpress/routes/user-routes')
const pollRoutes = require('./nextexpress/routes/poll-routes')
const mongoose = require("mongoose");
const cookieParser = require("cookie-parser"); // parse cookie header
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'
const nextapp = next({ dev })
const handle = nextapp.getRequestHandler()
const bodyParser = require('body-parser');
// mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/kb', { useNewUrlParser: true });
mongoose.connect('mongodb://localhost:27017/kb')
console.log(process.env.MONGODB_URI)
const connection = mongoose.connection;
const baseURL = urlObject.baseURL
const PORT = process.env.PORT || 3000
connection.once('open', function () {
console.log("MongoDB database connection established successfully");
})
nextapp.prepare().then(() => {
const app = express();
console.log(process.env.PORT, '----port here ----')
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/api/auth", authRoutes);
app.use("/api/kb", KBRoutes);
app.use('/api/user', userRoutes)
app.use('/api/poll', pollRoutes)
app.get('/posts/:id', (req, res) => {
return nextapp.render(req, res, '/article', { id: req.params.id })
})
app.get('/redirect/:id', (req, res) => {
return nextapp.render(req, res, '/redirect')
})
app.all('*', (req, res) => {
return handle(req, res)
})
app.listen(PORT, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${PORT}`)
})
})
// connect react to nodejs express server
And the relevant route:
KBRoutes.get('/', (req, res) => {
console.log(KB.Model)
KB.find({}, (err, photos) => {
res.json(kbs)
})
})
I am able to get to each one of the routes. Before this was working, when I had the NextJS React portion split into a separate domain therefore separate server.js files. Once I introduced NextJs thats when this problem arose. Any help would be greatly appreciated.
It looks like the relevant route is trying to return json(kbs), but kbs doesn't seem to be defined. Returning the result of your find query would make more sense to me, including a nice error catcher and some status for good practice. Catching errors should tell you what's going wrong, i would expect an error in your console anyway that would help us out finding the answer even more.
KB.find({}, (err, photos) => {
if (err) res.status(401).send(err)
res.status(200).json(photos)
})

get data from async function

i'm trying to do a little website like sickgearr for my seedbox :
i want a search form which will send a search query to my torrent providers using this api : https://github.com/JimmyLaurent/torrent-search-api
i managed getting text from the form, making the api calls and get results printed in the console.
but when i try to pass them to the soon to-become result page, i'm only passing promises and i don't quite understand the principle of promises.
If someone could help me resolve my issues i'd be really really gratefull or atleast give me some hints !
Here is my code made up from several ejs, nodejs begginers tutorials :
const express = require('express');
const bodyParser = require('body-parser');
const app = express()
const TorrentSearchApi = require('torrent-search-api');
const tableify = require('tableify');
TorrentSearchApi.enableProvider('Yggtorrent','Login', 'Password');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs')
async function search(query){ // Search for torrents using the api
var string = query.toLowerCase();
//console.log(string);
const torrents = await TorrentSearchApi.search(string,'All',20); // Search for legal linux distros
return(JSON.stringify(torrents));
}
app.get('/', function (req, res) {
res.render('index');
})
app.post('/', function (req, res) {
var rawTorrent = search(req.body.torrent);
var page = tableify(rawTorrent); //printing rawtorrent will only give me "promise"
res.render('results',page);
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
Your search function is using async/await.
It means the search function is asynchrone and returns a Promise.
You should await its result (line 23).
https://javascript.info/async-await
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const TorrentSearchApi = require('torrent-search-api')
const tableify = require('tableify')
TorrentSearchApi.enableProvider('Yggtorrent','Login', 'Password')
app.use(express.static('public'))
app.use(bodyParser.urlencoded({ extended: true }))
app.set('view engine', 'ejs')
const search = async query => {
const loweredQuery = query.toLowerCase()
const torrents = await TorrentSearchApi.search(loweredQuery, 'All', 20)
return JSON.stringify(torrents)
}
app.get('/', (_, res) => res.render('index'))
app.post('/', async (req, res) => {
const torrents = await search(req.body.torrent) // Right here
const htmlTable = tableify(torrents)
res.render('results', htmlTable)
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})

Categories

Resources