When i try to put a multiline string into a mongoose database it doesnt want to work. It just saves one line of the string.
Logging content to console:
Website result:
EJS Code
<% posts.forEach(function(post){ %>
<div class="card mb-2" style="width: 100%;">
<div class="card-body">
<% if(user.admin == true || user.id == post.authorid){ %>
<form action="/deletepost/<%= post.id %>" method="post">
<button type="submit" class="btn btn-sm btn-danger btn-block">Delete</button>
</form>
<br>
<% } %>
<h5 class="card-title"><%= post.authorname %></h5>
<h6 class="card-subtitle mb-2 text-muted"><%= post.date %></h6>
<hr>
<p class="card-text"><%= post.content %></p>
</div>
</div>
<% }); %>
Mongoose model:
const PostSchema = new mongoose.Schema({
content: {
type: String
}
})
How i save to database:
var newPost = {content, authorid, authorname};
Post.create(newPost, function(err, newlyCreated){
if(err){
console.log(err);
} else {
res.redirect("/app")
}
});
I use express & ejs if that matters.
Related
I am trying to create a registration form where a potential user is typing in their desired username it checks against the existing Mongo DB User Schema to see if that exact name exists.
The form I have is here:
<form class="needs-validation" action="/register" method="POST" novalidate>
<div class="text-center mb-3">
<p class="lead">Welcome to the team! We just need a few things to get started.</p>
<div class="row">
<div class="col-md-6 mb-4">
<div class="form-outline">
<input
type="text"
id="first_name"
name="first_name"
class="form-control"
required
/>
<label class="form-label" for="first_name"
>First name</label
>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Thats not right</div>
</div>
</div>
<div class="col-md-6 mb-4">
<div class="form-outline">
<input
type="text"
id="last-name"
name="last-name"
class="form-control"
required
/>
<label class="form-label" for="last-name"
>Last name</label
>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Thats not right</div>
</div>
</div>
</div>
<!-- Email input -->
<div class="form-outline mb-4">
<input
type="email"
id="register_email"
name="register_email"
class="form-control"
required
/>
<label class="form-label" for="register_email">Email</label>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Thats not right</div>
</div>
<div class="text-center mb-3">
<div class="form-outline mb-4">
<input type="text" id="register_username" name="register_username" class="form-control" placeholder="enter your username" required />
<label class="form-label" for="register_username">Username</label>
<div id="username-check"></div>
</div>
<!-- Password input -->
<div class="form-outline mb-4">
<input type="password" id="register_password" name="register_password" class="form-control" required/>
<label class="form-label" for="register_password">Password</label>
</div>
</div>
<!-- Submit button -->
<div class="text-center">
<button type="submit" id="register" class="btn btn-lg btn-rounded bg-insider link-dark mb-3 fw-bold" disabled>
Lets Go! <i class="fa-solid fa-gauge-max"></i>
</button>
</div>
</form>
I have this script code working on the page to take the user input and check to a get route that should be checking my MongoDB:
$('#register_username').on('keyup', function () {
$.get('/usercheck?username=' + $(this).val().toLowerCase(), function (response) {
$('#username-check').text(response.message);
console.log('')
var btn = document.getElementById('register');
btn.disabled = true;
if ($('#username-check').html() === "user exists") {
$('#username-check').text('username not available').css('color', 'red');
}
else {
console.log($('#register_username').val())
$('#username-check').text('username is available').css('color', 'green');
btn.disabled = false;
}
})
});
This is the route it calls to check the database:
var express = require("express"),
router = express.Router(),
passport = require("passport"),
User = require("../models/user");
router.get('/usercheck', function(req, res) {
console.log(req.query);
User.findOne({username: req.query.register_username}, function(err, username){
if(err) {
console.log(err);
}
var message;
if(username) {
console.log(username);
message = "user exists";
console.log(message);
} else {
message= "user doesn't exist";
console.log(message);
}
res.json({message: message});
});
});
module.exports = router;
In case this helps, this is the user Schema in the database:
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = new mongoose.Schema({
username: String,
password: String,
email: String,
isAdmin: { type: Boolean, default: false }
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User",UserSchema);
I am not sure what I am missing but anything would be extremely helpful. Thanks in advance!
Just so this question can be closed successfully:
Changing /usercheck?username= to /usercheck?register_username= did the trick, because this query param was used in the form:
$('#register_username').on('keyup', function () {
$.get('/usercheck?register_username=' + $(this).val().toLowerCase(), function (response) {
$('#username-check').text(response.message);
console.log('')
var btn = document.getElementById('register');
btn.disabled = true;
if ($('#username-check').html() === "user exists") {
$('#username-check').text('username not available').css('color', 'red');
}
else {
console.log($('#register_username').val())
$('#username-check').text('username is available').css('color', 'green');
btn.disabled = false;
}
})
});
I'm creating facebook like social media app using nodejs and ejs. I'm getting error " Cannot read property 'contentType' of undefined". But I get this error on profile.ejs and not on newsfeed.ejs. profile.ejs render photo if there's photo in the post but if I post a post with text only,this "Cannot read property 'contentType' of undefined" error occur.
app.js
app.get("/newsfeed", function(req, res){
if(req.isAuthenticated()){
Post.find({}, function(err, foundItem){
if(err){
console.log(err);
} else {
const loggedUser = req.user;
res.render("newsfeed", {posts: foundItem, loggedUser: loggedUser, foundUser: "undefined"});
}
}).sort({date: -1});
} else {
res.redirect("/login");
}
});
app.get("/profile/:userProfile", function (req, res) {
const userId = req.params.userProfile;
const loggedUser = req.user
if(req.isAuthenticated){
User.findById(userId, function(err, foundUser){
if(err){
console.log(err);
} else {
res.render("profile", {foundUser: foundUser, loggedUser:loggedUser});
}
}).sort({date: -1});
}
})
newsfeed.ejs
<% posts.forEach( function(post) { %>
<div class="post">
<!-- Post contents -->
<%= post.name %>
<p class="date"><%= post.date %></p>
<p class="content"><%= post.content %></p>
<% if(post.img != "undefined") { %>
<div class="mediaFiles">
<div class="imageOverlay"><i class="fas fa-times"></i></div>
<img src="data:image/<%=post.img.contentType%>;base64,
<%=post.img.data%>" class="image" onerror="this.style.display='none'">
</div>
<% } %>
<hr>
<% }); %>
profile.ejs
<% foundUser.post.forEach( function(post) { %>
<div class="post">
<!-- Post contents -->
<%= post.name %>
<p class="date"><%= post.date %></p>
<p class="content"><%= post.content %></p>
<% if(post.img != "undefined" || post.img != null || post.img != "") { %>
<div class="mediaFiles">
<div class="imageOverlay"><i class="fas fa-times"></i></div>
<img src="data:image/<%=post.img.contentType%>;base64,
<%=post.img.data%>" class="image" onerror="this.style.display='none'">
</div>
<% } else { %>
<div class="imageOverlay"><i class="fas fa-times"></i></div>
<img src="#" class="image" onerror="this.style.display='none'">
</div>
<% } %>
This is form and displays single data in this.
singlepassword.js
<html>
<%- include("./partials/head.ejs") %>
<body>
<%- include("./partials/nav.ejs") %>
<div class="container" style="height:379px;">
<div class="row m-3">
<form class="col-sm-10 offset-sm-1" method="POST" action="/details">
<div class="row">
<h3 class="col-sm-9 text-info mt-2 mb-2">View Single data</h3>
<span class="col-sm-3 btn-group">
<a role="button" class="btn btn-success" data-doc="<%= selection._id%>">Update</a>
<a role="button" class="btn btn-danger delete" data-doc="<%= selection._id%>">Delete</a>
<a role="button" class="btn btn-secondary" href="/details">Cancel</a>
</span>
</div>
<input type="hidden" value="<%= selection._id%>"/>
<div class="form-group"><label class="form-label text-light" for="website">Website</label><input class="form-control text-dark" id="website" type="text" name="website" value="<%= selection.website %>" required></div>
<div class="form-group"><label class="form-label text-light" for="username">User Name</label><input class="form-control text-dark" id="username" type="text" name="username" value="<%= selection.username %>" required></div>
<div class="form-group"><label class="form-label text-light" for="pass">Password</label><input class="form-control text-dark" id="pass" type="password" name="password" value="<%= selection.password %>" required></div>
</form>
</div>
</div>
<%- include("./partials/footer.ejs") %>
<script>
const trashcan = document.querySelector('a.delete');
trashcan.addEventListener('click', (e) => {
const endpoint = `/details/${trashcan.dataset.doc}`;
fetch(endpoint, {
method: 'DELETE',
})
.then(response => response.json())
.then(data => window.location.href = data.redirect)
.catch(err => console.log(err));
});
</script>
</body>
</html>
this is the routing file and put request includes in this file.
passwordRoutes.js
const express = require('express');
const Password = require('../models/passwordList');
const router = express.Router();
//update data
router.put((req,res)=>{
const id = req.params.id;
Password.findByIdAndUpdate(id)
.then((result) =>{
console.log(result);
})
.catch((err) =>{
console.log(err);
});
})
module.exports = router ;
this file includes mongoose schemas.
passwordList.js
const mongoose = require ('mongoose');
const Schema = mongoose.Schema;
const passwordSchema = new Schema({
website:{
type: String,
required : true
},
username:{
type: String,
required : true
},
password:{
type:String,
required:true
}
}, {timestamps: true});
const PasswordList = mongoose.model('PasswordList', passwordSchema);
module.exports = PasswordList;
How do update data when clicking the update button using put request?
After update data , should redirect details.js page
Data is not getting captured in mongodb . For frontend I am using angular and at backend I am using node js. I tested the backend api using postman , data is getting captured in mongoDb , where as when I am submitting from an angular form data is not getting captured.
//UI logic
<div class="row mt-5">
<div class="col-md-6 mx-auto">
<div class="card">
<div class="card-header">
<h3>Register</h3>
</div>
<div class="card-body">
<form>
<div class="form-group">
<label>Email:</label>
<input type="text" class="form-control" name="email" [(ngModel)]="registerUserData.email" email required>
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" class="form-control" name="password" [(ngModel)]="registerUserData.password" required>
</div>
<button (click)="registerUser()" class="btn btn-info float-right">Register</button>
</form>
</div>
</div>
</div>
</div>
//service
private urlR="http://localhost:3000/register";
private urlL="http://localhost:3000/login";
constructor(private httpClient:HttpClient) { }
registerUser(abc){
return this.httpClient.post<any>(this.urlR,abc);
}
//submit method
registerUser() {
this.authService.registerUser(this.registerUserData)
.subscribe(
res=> console.log(res),
err=> console.log(err)
)
}
//backend node
app.post('/register' , (req,res) => {
const newUser = new Expo({
email:req.body.email,
password:req.body.password
});
newUser.save( (err , registeredUser) => {
if(err) {
console.log(err);
} else {
res.status(200).send(registeredUser);
}
});
});
I want to pass data from MySQL database in datalist option. My application is written in express js using ejs view. I can't figure out how to pass database values to list in JavaScript and how to pass this list to ejs file.
add.js:
module.exports = {
addProductPage: (req, res) => {
let query = "SELECT shipper_names.Shipper_ID, shipper_names.Shipper_Name FROM shipper_names";
conn.query(query, (err, results) => {
if (err) {
return res.status(500).send(err);
}
res.render('add-product.ejs', {
title: "Add Product",
shipper_names: results[0],
message: ''
});
});
}
}
EJS file:
<!doctype html>
<html lang="en">
<div>
<a class="float-right" href="/" title="Home">Home</a>
</div>
<div class="contnainer">
<% if (message) {%>
<p class="text-container text-danger">
<%= message %>
</p>
<%}%>
<% if (shipper_names) {%>
<form class="add-player-form" action="" method="POST" enctype="multipart/form-data">
<div>
<input type="text" id="shippers_names" list="languageList" />
<!--your input textbox-->
<datalist id="languageList">
<option value=""> </option>
</datalist>
</div>
<button type="submit" class="btn">Add Product</button>
</form>
<% } else { %>
<p class="text center">Product Not Found. Go HereTo Add Product.</p>
<% } %>
</div>
</html>
module.exports = {
addProductPage: (req, res) => {
let query = "SELECT * from shipper_names"
conn.query(query, (err, results) => {
if (err) {
return res.status(500).send(err);
}
res.render('add-product.ejs', {
shipper_names: results
});
});
},
<div>
<input type="text" id="txtAutoComplete" list="names" />
<!--your input textbox-->
<datalist id="names">
<% shipper_names.forEach((shipper_names, index)=>{%>
<option id=<%= shipper_names.Shipper_ID%>>
<%= shipper_names.Shipper_Name%></option>
<%})%>
</datalist>
</div>
this is working