i'm trying to make an update functionality but it doesn't update the model :( First i make a get request to get the data from the server and populate it in form(handlebars)
so, here's the router:
router.get('/edit/:id', async (req, res) => {
const warum = await Warum.findById(req.params.id)
res.render('edit', warum);
});
router.post('/edit/:id', (req, res) => {
return Warum.findOneAndUpdate(req.params.id, { new: true }, {
title: req.body.title,
description: req.body.description,
})
.then(() => {
res.redirect('/warum');
})
.catch((err) => {
console.log(err);
});
});
that's the form:
<form method="post">
<h2>Beitrag bearbeiten</h2>
<ul class="noBullet">
<li>
<label for="title">Titel:</label>
<input type="text" name="title" value="{{title}}" />
</li>
<li>
<label for="description">Beschreibung:</label>
<textarea class="texterea" name="description">
{{description}}
</textarea>
</li>
<div>
<button class="login-button">save</button>
</div>
</ul>
</form>
and that's the schema:
const mongoose = require('mongoose')
const WarumSchema = new mongoose.Schema({
title: String,
description: String,
});
const Warum = mongoose.model('Warumschema', WarumSchema);
module.exports = Warum;
I tried to change the route from post to put, but then it says 404. After clicking the save button it just redirects me, but the result is not edited.
Related
Hi there im having difficulty with my post request for login,
I've managed to get register working and i redirect it to login so i can attempt, the account registered goes onto mongodb correctly, from some testing with multiple logs, turns out the post for login isnt effecting it, and it simply redirects again to login, unsure how that is
heres what i got
const mongoose = require('mongoose')
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
}
})
module.exports = mongoose.model('users', userSchema)
This is for where im storing the users info for the login page
<h1>Login</h1>
<form action="/login" method="GET">
<div>
<label for="name">Name</label>
<input type="name" id="name" name="name" required>
</div>
<div>
<label for="email">Email</label>
<input type="email" id="email" name="email" required>
</div>
<div>
<label for="password">Password</label>
<input type="password" id="password" name="password" required>
</div>
<button type="submit">Login</button>
</form>
Register a User
Register is the same as this only with the href relating to this login page
const express = require('express')
const router = express.Router()
const users = require('../models/users')
const book = require('../models/book')
router.get('/home', async (req, res) => {
let books
try {
books = await book.find().sort({ createdAt: 'desc' }).limit(10).exec()
} catch {
books = []
}
res.render('home.ejs', { books: books })
})
//Login user
router.get('/', (req, res) => {
res.render('index.ejs')
})
router.get('/login', async (req, res) => {
res.render('login')
})
router.post('/login', async (req, res) => {
console.log("HI")
try{
const valid=await users.findOne({name:req.body.name})
if (valid.password===req.body.password){
res.render('home')
}
else{
console.log("HI")
res.send("Incorrect Password Try again?")
res.render('home')
}
}catch{
console.log("HI")
res.render('home')
}
})
//Register and upload to DB
router.post('/', async (req, res) => {
const user = ({
name: req.body.name,
email: req.body.email,
password: req.body.password,
})
await users.insertMany([user])
res.redirect('/')
})
module.exports = router
In your form you have mentioned method as "GET" . It is a post request so method should be "POST".
<form action="/login" method="post">
am new to nodeJS am trying to post the collection when the button is been clicked, i don't is posting because am getting an error:undefined, when i console the req.body please what am doing wrong here. is there something am not doing
Here's my code.
//create.ejs file
<form action="/blogs" method="post">
<div>
<label>Title</label>
<input name="title" type="text"/>
</div>
<div>
<label>Content header</label>
<input name="content" type="text"/>
</div>
<div>
<label>Content Body</label>
<textarea name="body"></textarea>
</div>
<div class="button">
<button>Post content</button>
</div>
</form>
//app.js file
const express = require("express")
const app = express()
const mongoose = require("mongoose")
const Schema = mongoose.Schema;
const BlogPost = new Schema({
title:{
type: String,
required: true
},
content: {
type: String,
required: true
},
body: {
type: String,
required: true
}
})
const Blog = mongoose.model("Blog", BlogPost)
module.exports = Blog;
app.post("/blogs", (req, res) => {
const blogs = new Blog({
title:req.body.title,
content: req.body.content,
body: req.body.body,
})
blogs.save()
.then(result => console.log(result))
.catch(err => console.log(err))
})
You must write
<input type="submit" name="Post content" value="Post content">
instead of this Post content
In the button element add
<button type="submit">Post content</button>
I forget to add urlencoded method.
app.use(express.urlencoded({ extended: true }))
NextJS Code:
const Home: NextPage = () => {
return (
<div className={styles.container}>
<form action="http://localhost:2000/register" method="post">
<label htmlFor="name">Name:</label>
<input type="text" id="first" name="first" />
<label htmlFor="email">Email</label>
<input type="text" id="last" name="last" />
<button type="submit">Submit</button>
</form>
</div>
)
}
Express Code:
router.post('/register', async (req: Request, res: Response) => {
const user = await User.create({
name: req.body.name,
email: req.body.email,
});
return res.status(200).json(user);
});
The schema for that is:
import mongoose from 'mongoose'
const userSchema = new mongoose.Schema({
name: String,
email: String,
});
export const User = mongoose.model('User', userSchema);
When I enter name + email, its only saving the _id, nothing else, why?
I am working on personal project. one of common functionality i am implementing is allowing users to update their profile but having hard time doing it.
here is what i did so far
form
<form
action="/users/doctor-profile?_method=PUT"
method="POST"
enctype="multipart/form-data"
>
<input type="hidden" name="_method" value="PUT" />
<div class="form-group">
<input
type="text"
class="form-control"
id="name"
name="name"
/>
</div>
<div class="form-group">
<label for="phone">Phone</label>
<input
type="tel"
class="form-control"
id="formGroupExampleInput"
name="phone"
/>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input
type="email"
class="form-control"
id="formGroupExampleInput"
name="email"
/>
</div>
<button type="submit" class="btn btn-primary">Save changes</button>
</form>
here is my user model
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
phone: {
type: String,
required: true,
},
});
const User = mongoose.model("User", UserSchema);
module.exports = User;
here is my post route
router.post("/users/doctor-profile", (req, res) => {
const { name, email,phone } = req.body;
const _id = ObjectId(req.session.passport.user._id);
console.log(_id)
USer.findOne({ _id: _id })
.then((user) => {
if (!user) {
req.flash("error_msg", "user not found");
res.redirect("/users/doctor-profile");
}
if (typeof name !== "undefined") {
user.name = name;
console.log(user.name);
}
if (typeof email !== "undefined") {
user.email = email;
}
if (typeof phone !== "undefined") {
user.phone = phone;
}
user.save().then((User) => {
req.flash("success_msg", "details updated successfully");
res.redirect("/users/profile");
});
})
.catch((err) => console.log(err));
});
console output
application running on port 5000
mongodb connection successfull
5ef5bc20261beb1e6c1c25a3
but it does not update fields in database.
try this:
user.save(function (err, resolve) {
if(err)
console.log('db error', err)
// saved!
});
You had a typo in your post route js file
here is the code you got the typo on:
USer.findOne({ _id: _id })
USer should be User
When I submit my form I get the following error: Error [ValidationError]: System validation failed: lastName: Path lastName is required., firstName: Path firstName is required.
I'm not sure what's causing this, when I console.log(formData) I get the data I submitted into the form.
App.js
const express = require('express')
const app = express();
const mongoose = require('mongoose');
const dotenv = require ('dotenv/config');
const System = require('./models/System');
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.get('/', (req,res) => {
res.render('index.ejs');
});
app.post('/post-feedback', (req, res) => {
const formData = {
firstame: req.body.firstName,
lastname: req.body.lastName,
assetTag: req.body.assetTag
}
const system = new System(formData);
system.save()
.then(result => {
console.log(result);
})
.catch(err => {
console.log(err);
});
});
Model:
const mongoose = require('mongoose');
var SystemSchema = new mongoose.Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
assetTag: {
type: Number,
required: true
}
});
module.exports = mongoose.model('System', SystemSchema);
Form:
<form action="/post-feedback" method="POST">
<div class="form-group">
<label for="firstName">First Name: </label>
<input type="text" class="form-control" id="firstName" name="firstName">
</div>
<div class="form-group">
<label for="lastName">Last Name: </label>
<input type="text" class="form-control" id="lastName" name="lastName">
</div>
<div class="form-group">
<label for="assetNum">Asset Tag: </label>
<input type="text" class="form-control" id="assetTag" name="assetTag">
</div>
<button type="submit" name="submit" class="btn btn-primary">Submit</button>
</form>
The only one reason why you got some error it's because you're typo on your formData. It must be firstName and lastName, make sure it same with your Schema field and then Make Sure your assetTag is a number, because your Schema type is number.
You can try with this code below:
app.post('/post-feedback', (req, res) => {
const formData = {
// you're typo here: firstame
firstName: req.body.firstName,
// you're typo here: lastname
lastName: req.body.lastName,
// must be number
assetTag: parseInt(req.body.assetTag);
}
const system = new System(formData);
system.save()
.then(result => {
console.log(result);
})
.catch(err => {
console.log(err);
});
});
I hope it can help you.
app.post('/post-feedback', (req, res) => {
const system = new System(req.body);
system.save()
.then(result => {
console.log(result);
})
.catch(err => {
console.log(err);
});
});
i think above code should be work.