I am trying through node js, express and mongoose to create a way to add the same mongoose Schema more than one time I want to use a trigger button. I have to restart the server to add more to the DB.
Later on I want to change it through a counter but first I need to get this working.
I am trying to solve it on my own but I got stuck, thank you for your help !
the app.js I use as server.
/app.js
const express = require('express');
const { default: mongoose } = require('mongoose');
const path = require('path');
const db = require("./database");
const app = express();
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.use(express.static('DB'));
app.use('/Dev', express.static(path.join(__dirname, 'Dev', 'public')));
//Export function to new a .js file
var ClickyClicky = new mongoose.Schema({
name: {
type: String,
require: true
}},
{
timestamps: true, //time
}
);
var Clicky = mongoose.model('Click', ClickyClicky, 'clickystore');
var Clicks = new Clicky({ name: 'Test' });
//Export function to new a .js file
//Save button trigger.
app.post('/test', (req, res) => {
Clicks.save(function (err, book) {
if (err) return console.error(err);
console.log(book.name + " saved to bookstore collection.");
});
});
//Save button trigger.
app.post('/alfa', (req, res) => {
Clicks.save(function (err, name) {
if (err) return console.error(err);
console.log(name.name + " saved to name collection.");
});
});
// // 404 page
app.all('*', (req, res) => {
res.status(404).send('<h1>404, Page not found !</h1>');
});
app.listen(5000, () => {
console.log('Server started at http://localhost:5000');
});
/client.js
console.log('Client code running');
const testButton = document.getElementById('Button');
testButton.addEventListener('click', function(e) {
console.log('Butten was clicked');
fetch('/test', {method: 'POST'})
.then(function(response) {
if(response.ok) {
console.log('Click was recorded');
return;
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
});
const testButton2 = document.getElementById('Button2');
testButton2.addEventListener('click', function(e) {
console.log('Butten was clicked');
fetch('/alfa', {method: 'POST'})
.then(function(response) {
if(response.ok) {
console.log('Click was recorded');
return;
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="Button">Click me for a test!</button>
<button id="Button2">Click me for a test1!</button>
</body>
<script src="./Dev/Client.js"></script>
</html>
\database.js
require('dotenv').config();
const mongoose = require('mongoose');
mongoose.set("strictQuery", false);
mongoose.connect(process.env.MONGOOB_URI, () => {
console.log("Connected to MongoDB");
});
I solved my issue with adding, unique: false to my mongoose schema and deleted the old input from the BD
Related
i am testing this url==> (http://localhost:8800/api/users/634ed4af41fb0169e999deb2/follow) on
postman, it works in case of without having (/follow), But when i use this url every time i get this error=====>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot PUT /api/users/634ed4af41fb0169e999deb2/follow%0A</pre>
</body>
</html>
Below i am getting issue in using // app.use('/api/users',userRoutes)//. This will call the router present in the users.js
index.js
const express= require("express");
const app=express();
const mongoose=require("mongoose");
const dotenv=require("dotenv");
const helmet=require("helmet");
const morgan=require("morgan");
const userRoutes=require("./routes/users")
const authRoutes=require("./routes/auth");
dotenv.config();
mongoose.connect(process.env.MONGO_URL,
{useNewUrlParser: true, useUnifiedTopology: true}, ()=>{
console.log("connected to database");
});
//middleware
app.use(express.json());
app.use(helmet());
app.use(morgan("common"));
//cutom middleware for Routing
app.use('/api/users',userRoutes);
app.use('/api/auth',authRoutes);
app.listen(8800,()=>{
console.log("backend server running");
})
here in user.js controller are not able to log the console present at the top position.
user.js
const router=require("express").Router();
const bcrypt=require('bcrypt');
const User = require("../models/User");
//follow user
router.put("/:id/follow", async (req , res)=>{
console.log(req.body.userId === req.params.id.trim());
if(req.body.userId !== req.params.id){
try {
const user= await User.findById(req.params.id);
const currentUser= await User.findById(req.body.userId);
if(!user.followers.includes(req.body.userId)){
await user.updateOne({$push:{followers:req.body.userId}});
await currentUser.updateOne({$push:{followings:req.params.id}});
res.status(200).json("user has been follwed")
}else{
res.status(403).json('you all ready followed')
}
} catch (error) {
res.status(500).json(error)
}
}
else{
res.status(403).json("you cant follow yourself")
}
})
I'm using MEAN stack as my back-end. this is my server js file
const users = require('./routes/users');
app.get('/', (req, res) => {
res.send('Invalid endpoint');
});
This is my routes file users.js
router.get('/jobdetail', function(req,res) {
console.log('fetching jobs');
jobDetails.find({}, (err,jobs) => {
if(err) {
console.log(err);
}
else {
res.json(jobs);
}
});
});
when I run it the postman bu url:
localhost:3000/api/jobdetail
Instead of the data from MongoDB I get the response as
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
<script type="text/javascript" src="http://gc.kis.v2.scr.kaspersky-labs.com/D11634C0-514E-C94E-9DFD-54EBD0B16E5F/main.js" charset="UTF-8"></script>
</head>
<body>
<pre>Cannot GET /api/jobdetail</pre>
</body>
</html>
var api = require('../routes/users.js');
app.use('/api', api);
in your routes/users.js file :
var mongoose =require('mongoose');
var router = require('express').Router();
var conn = mongoose.connection;
conn.once("open", () => {
router.get('/jobdetail', function(req, res) {
jobDetails.find({}, (err,jobs) => {
if(err) {
console.log(err);
}
else {
res.json(jobs);
}
});
});
});
module.exports = router;
I'm getting the error as 404 not found while trying to post data using postman in chrome.Any kind of help would be highly appreciated.
I'm doing this application from the following link :https://www.youtube.com/watch?v=wtIvu085uU0
here is my code.
app.js
//importing modules
var express=require('express');
var mongoose=require('mongoose');
var bodyparser=require('body-parser');
var cors=require('cors');
var path=require('path');
var app=express();
const route=require('./router/route');
//connect to mongodb
mongoose.connect('mongodb://localhost:27017/contactlistapp');
//on connection
mongoose.connection.on('connected',()=>{
console.log('successfully connected to database mongodb #27017');
});
mongoose.connection.on('error',()=>{
if(err)
{
console.log('Error in database connection:'+err);
}
});
//port number
const port=3000;
//adding middleware-cors
app.use(cors());
//bodyparser
app.use(bodyparser.json());
//adding routes
app.use('/api',route);
//static files
app.use(express.static(path.join(__dirname,'public')));
//testing server
app.get('/',(req,res)=>{
res.send('foobar');
});
app.listen(port,()=>{
console.log('serve started at'+port);
});
route.js
const express=require('express');
const router=express.Router();
const contact=require('../models/contacts');
//retrieving contacts
router.get('/contacts',(req,res,next)=>{
contact.find(function(err,contacts){
res.json(contacts);
})
});
//retrieving data
router.get('/contacts',(req,res,next)=>{
res.send('Retrieving the contacts list');
});
//add contacts
router.post('./contact',(req,res,next)=>{
let newContact=new contacts({
first_name:req.body.first_name,
last_name:re.body.last_name,
phone:req.body.phone
})
newContact.save((err,contact)=>{
if(err){
res.json({msg: 'Failed to add contact'});
}
else{
res.json({msg: 'contact added successfully'});
}
})
});
//delete contacts
router.delete('./contact/:id',(req,res,next)=>{
contact.remove({_id:req.params.id},function(err,result){
if(err)
{
res.json(err);
}
else{
res.json(result);
}
})
});
module.exports=router;
contacts.js
const mongoose=require('mongoose');
const ContactSchema=mongoose.Schema({
first_name:{
type:String,
required:true
},
last_name:{
type:String,
required:true
},
phone:{
type:String,
required:true
}
});
const contact=module.exports=mongoose.model('contact',ContactSchema);
Getting the following error in postman:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /api/contacts</pre>
</body>
</html>
The following is the json data i'm trying to post:
{
"first_name":"anand",
"last_name":"reddy",
"phone":"1234567813"
}
router.post('./contact' should be router.post('/contacts
I'm fairly new to Nodejs and I'm building an app that ssh to a remote machine and get a tail -f of a log file.
The lines of the log file I'm receiving I'm sending to the client via socket-io (ver. 2.0.3)
Now I'm facing a problem that when a second browser tries to tail a different log, the new log is sent to both of the browsers instead of only the one who made the request.
I'm not sure if it's a problem with my socket-io code or the child_process.
Here's the server:
const express = require('express'),
app = express(),
path = require('path'),
bodyParser = require('body-parser'),
logger = require('morgan'),
server = require('http').Server(app),
io = require('socket.io')(server),
spawn = require('child_process').spawn,
events = require('events'),
eventEmitter = new events.EventEmitter();
// Fix body of requests
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// Log the requests
app.use(logger('dev'));
// Serve static files
app.use(express.static(path.join(__dirname, '.')));
// Add a basic route – index page
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
io.on('connection', (socket) => {
console.log(`client connected ${socket.client.id}`);
eventEmitter.on('tail', (data) => {
socket.tail = spawn('ssh', ['root#' + 'quality-p.company.com', 'tail -f', data.service], { shell: true });
socket.tail.stdout.on('data', (data) => {
console.log(`got new data ${data.toString()}`);
socket.emit('newLine', {line: data.toString().replace(/\n/g, '<br />')});
});
});
});
app.get('/tail', (req, res) => {
eventEmitter.emit('tail', req.query);
res.sendStatus(200);
});
// Bind to a port
server.listen(3005, () => {
console.log('running on localhost:' + 3005);
});
Client:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="./node_modules/socket.io-client/dist/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(() => {
let socket = io();
socket.on('connect', () => {
console.log('connected');
});
socket.on('newLine', (data) => {
console.log(`new data: ${data.line}`);
$("#tailing").append(data.line);
});
$('#tail').click(() => {
$.get('/tail', {
service: $('#service').val()
});
});
});
</script>
<title>Title</title>
</head>
<body>
<select id="service">
<option id="tnet" value="/var/log/tnet">tnet</option>
<option id="consul" value="/var/log/consul">consul</option>
</select>
<button id="tail">tail</button>
<div id="tailing" style="background-color: antiquewhite;">
</div>
</body>
</html>
Server
const express = require('express'),
app = express(),
path = require('path'),
bodyParser = require('body-parser'),
logger = require('morgan'),
server = require('http').Server(app),
io = require('socket.io')(server),
spawn = require('child_process').spawn;
// Fix body of requests
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
// Log the requests
app.use(logger('dev'));
// Serve static files
app.use(express.static(path.join(__dirname, '.')));
// Add a basic route – index page
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
var tails = {};
io.on('connection', (socket) => {
console.log(`client connected ${socket.client.id}`);
socket.on('tail', (data) => {
socket.join(data.service);
if (typeof tails[data.service] == "undefined") {
tails[data.service] = spawn('ssh', ['root#' + 'quality-p.company.com', 'tail -f', data.service], {
shell: true
});
tails[data.service].stdout.on('data', (data) => {
console.log(`got new data ${data.toString()}`);
io.to(data.service).emit('newLine', {
line: data.toString().replace(/\n/g, '<br />')
});
});
}
});
});
// Bind to a port
server.listen(3005, () => {
console.log('running on localhost:' + 3005);
});
Client
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="./node_modules/socket.io-client/dist/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(() => {
let socket = io();
socket.on('connect', () => {
console.log('connected');
});
socket.on('newLine', (data) => {
console.log(`new data: ${data.line}`);
$("#tailing").append(data.line);
});
$('#tail').click(() => {
socket.emit('tail', {
service: $('#service').val()
});
});
});
</script>
<title>Title</title>
</head>
<body>
<select id="service">
<option id="tnet" value="/var/log/tnet">tnet</option>
<option id="consul" value="/var/log/consul">consul</option>
</select>
<button id="tail">tail</button>
<div id="tailing" style="background-color: antiquewhite;">
</div>
</body>
</html>
I am studying node and express. I have a table of inventory item and I want to view this on my web browser that's why I used socket.io with express.
But when there's a connection I can't load the data. Here's my code:
server.js
var express = require('express');
var app = express();
var mysql = require('mysql');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 8000;
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'node'
});
app.use(express.static(__dirname + '/public'));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
connection.connect();
/**example from express
connection.connect();
connection.query('SELECT * FROM inventory', function(err, rows, fields){
if(err) throw err;
console.log(rows);
});
connection.end();
**/
function loadList() {
connection.query('SELECT * FROM inventory', function(err, rows, fields){
if(err) throw err;
return rows;
});
}
io.on('connection', function(socket){
console.log('A user is connected!!');
socket.on('inventory list', function(data){
return 'hello world'; // i pass a simple return to test if this can return something
/*
connection.query('SELECT * FROM inventory', function(err, rows, fields){
if(err) throw err;
console.log(rows);
});
*/
});
socket.on('disconnect', function() {
console.log('user disconnected!');
});
});
http.listen(8000, function() {
console.log('Listening on ' + port);
});
index.html
<!DOCTYPE>
<html>
<head>
<title>Invertory Sample</title>
<link rel="stylesheet" type="text/css" href="/bower_components/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="/bower_components/font-awesome/css/font-awesome.min.css" />
</head>
<body>
<p>sample</p>
<p class="test"></p>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script type="text/javascript" src="/bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
try {
var socket = io.connect('http://127.0.0.1:8000');
//console.log(socket);
}catch(e) {
console.log('ERROR OCURRED: ' + e);
}
if(socket !== undefined) {
socket.on('inventory list', function(data) { console.log(data); //i console but no response. });
}
</script>
</body>
</html>
Can you help me? I am extremely new in nodejs but I have some basic understanding. Or can you provide me a good example for this?
Thats all thanks.
In both, client and server, your are listening an event('inventory list'), but no one emits this event.
If you want to send the list to the client on conection you can try something like this on server:
io.on('connection', function(socket){
console.log('A user is connected!!');
socket.emit('inventory list', { list: 'mylist' });
socket.on('disconnect', function() {
console.log('user disconnected!');
});
});
http://socket.io/docs/server-api/