Assistance On CRUD Operations For Express App - javascript

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

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/

What does this error mean and how would I fix it: throw new TypeError('app.use() requires a middleware function')?

I am trying to create a login page and sign up page, my app.js gives me this error, I think it is the last line of this code. I can send you the other components(files) for this express app. I cannot understand what is causing this error.
const express = require('express');
const mongoose = require('mongoose');
// Routes
const authRoutes = require('./routes/authRoutes');
const app = express();
// middleware
app.use(express.static('public'));
app.use((err, req, res, next) => {
res.locals.error = err;
res.status(err.status);
res.render('error');
});
// view engine
app.set('view engine', 'ejs');
// database connection
const dbURI = '<database, username and password>';
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex:true })
.then((result) => app.listen(3000))
.catch((err) => console.log(err));
// routes
app.get('/', (req, res) => res.render('home'));
app.get('/smoothies', (req, res) => res.render('smoothies'));
app.use(authRoutes);
authRoutes.js
const { Router } = require('express')
const authController = require('./authController.js')
const router = Router();
router.get('/signup', authController.signup_get);
router.get('/signup', authController.signup_post);
router.get('/login', authController.login_get);
router.get('/login', authController.login_post);
module.export = router;
authController.js
module.exports.signup_get = (req, res) => {
res.render('signup');
}
module.exports.login_get = (req, res) => {
res.render('login');
}
module.exports.signup_post = (req, res) => {
res.send('signup');
}
module.exports.login_post = (req, res) => {
res.send('login');
}
You are exporting incorrectly in authRoutes.js.
Change this:
module.export = router;
to this:
module.exports = router;
FYI, a little debugging on your own by simply doing a console.log(authRoutes) should have been able to show you where to look for the problem. If you get an error when you attempt to use authRoutes, you look at what it is and where it came from to see why it's not working. This is basic debugging and there is an expectation that you've done basic debugging before you post your question here.

How to get access to variable from post into get method with mongoDB

i created variable in app.post, and i want to use it in app.get, but before this i added this one to my database, but i don't know how to get access to this variable in other function, here is my code
const express = require("express");
const { default: mongoose } = require("mongoose");
const app = express();
const port = 3000;
const Task = require(`./models/task`);
require("./db/moongose");
// sendFile will go here
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: false }));
app.get("/task", (req, res) => {
res.render("../public/mainPage.ejs", {tasks: mongoose});
});
app.post("/task", async (req, res) => {
const task = new Task({
description: req.body.task,
});
try {
await task.save();
console.log(task.description);
res.redirect("/task");
} catch (e) {}
});
app.listen(port);
console.log("Server started at http://localhost:" + port);
and all i want to do is get acces to task.description in app.get

Express rest api and mongoDB lowercase query

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?

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