I have created routes and models as below and data seems to be saved from postman.
UPDATE: Unable to save data after creating Angular services.
I have created a service which will save the product data on click event.
NODE JS CODE
\var\www\html\Express\nodeauthapp-master\app.js
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');
const mongoose = require('mongoose');
const config = require('./config/database');
// Connect To Database
mongoose.connect(config.database);
// On Connection
mongoose.connection.on('connected', () => {
console.log('Connected to database '+config.database);
});
const app = express();
const products = require('./routes/products');
...
...
app.use('/products', products);
\var\www\html\Express\nodeauthapp-master\routes\products.js
const express = require('express');
const router = express.Router();
var mongoose = require('mongoose');
const config = require('../config/database');
const Products = require('../models/products');
// Add Categories
router.post('/add', (req, res, next) => {
//res.send('Products addition');
//Create a model folder
let newProduct = new Products({
category_name: req.body.category_name,
product_name: req.body.product_name,
product_price: req.body.product_price,
product_image: req.body.product_image,
product_desc: req.body.product_desc,
product_status: req.body.product_status,
product_createdat: req.body.product_createdat,
product_updatedat: req.body.product_updatedat
});
Products.addProduct(newProduct, (err, user) => {
if(err){
res.json({success: false, msg:'Product unable to add'});
} else {
res.json({success: true, msg:'Products successfuly added!!'});
}
});
});
module.exports = router;
\var\www\html\Express\nodeauthapp-master\models\products.js
const mongoose = require('mongoose');
const config = require('../config/database');
// Products Schema
const ProductsSchema = mongoose.Schema({
category_name: {
type: String
},
product_name: {
type: String,
required: true
},
product_price: {
type: String,
required: true
},
product_image: {
type: String,
required: false
},
product_desc: {
type: String,
required: false
},
product_status: {
type: String,
required: true
},
product_createdat: {
type: String,
required: true
},
product_updatedat: {
type: String,
required: true
}
});
const Products = module.exports = mongoose.model('Products', ProductsSchema);
module.exports.addProduct = function(newProduct, callback){
newProduct.save(callback);
}
I am basically using this plugin : https://akveo.github.io/ng2-smart-table/#/
URL used : http://10.20.3.44:3000/products/add in postman, i get Success message.
ANGULAR 2 CODE
\src\app\layout\blank-page\blank-page.component.ts
#Component({
selector: 'app-blank-page',
templateUrl: './blank-page.component.html',
styleUrls: ['./blank-page.component.scss']
})
export class BlankPageComponent implements OnInit {
#Input() data: any;
constructor(private addproductService:AddproductService,
private flashMessage:FlashMessagesService,
private router: Router) { }
ngOnInit() { }
onRowSelect(event):void{
console.log(this.view_update_items_smart_data)
this.view_update_items_smart_data;
this.addproductService.productSave(this.view_update_items_smart_data).subscribe(data => {
console.log(data)
if(data.success){
this.flashMessage.show('Product successfully added', {cssClass: 'alert-success', timeout: 3000});
this.router.navigate(['/category-items']);
} else {
console.log('Failure')
this.flashMessage.show('Something went wrong', {cssClass: 'alert-danger', timeout: 3000});
this.router.navigate(['/category-items']);
}
});
}
view_update_items_smart_data = [
{
"category_name": "Meals",
"product_name": "South Meals",
"product_price": "35.00",
"product_image":"image1",
"product_desc": "South Meals",
"product_status" : "Yes",
"product_createdat" : "13/7/2017",
"product_updatedat" : "13/7/2017"
}
]
src\app\shared\services\addproduct.service.ts
#Injectable()
export class AddproductService {
view_update_items_smart_data: any;
constructor(private http:Http) { }
productSave(view_update_items_smart_data){
console.log('add service')
let headers = new Headers();
headers.append('Content-Type','application/json');
return this.http.post('http://10.22.3.44:3000/products/add', view_update_items_smart_data,{headers: headers})
.map(res => res.json());
}
}
I get failure message always, but through postman, data gets saved!!
Below is my console log in my browser.
Related
I've got a react project setup along with a server using the MERN stack.
I'm trying to implement longpolling into my project and its working all fine and dandy, but in my browser whenever i refresh the page without first updating the database to let the server answer the "get request", i get an error saying
Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.
Says it can be found in PollingTest.js:9
//Client
//PollingTest.js
import React, { useEffect } from 'react'
export default function PollingTest() {
async function LongPolling(){
const res = await fetch("http://localhost:3001/poll")
const data = await res.json()
console.log(data)
LongPolling();
}
useEffect(()=>{
LongPolling();
},[])
return (
<div>PollingTest</div>
)
}
//Server
//server.js
const express = require('express');
const app = express();
const path = require("path");
const mongoose = require('mongoose');
const db = {};
const Schema = mongoose.Schema;
const errandSchema = new Schema({
roomNr: {type: Number, required: true, min: 0},
category: {type: String, required: true},
roles: [String],
title: {type: String, required: true},
text: {type: String, required: false},
status: {type: Number, required: true, min: 0, max: 2},
highPriority: {type: Boolean, required: true},
opened: {type: Date, required: true},
closed: {type: Date, required: false}
});
db.errand = mongoose.model('Errand', errandSchema);
const cors = require('cors');
app.use(cors({ origin: "http://localhost:3000" }));
app.use(express.json());
const mongoURI = "mongodb://DESKTOP-LHCS5UA:27017/database";
const port = process.env.PORT || 3001;
mongoose.connect(mongoURI)
.then(() => {
console.log('Connected to mongo!');
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
});
})
.catch((err) => {
console.log(err);
process.exit();
});
app.get('/poll', async (req, res, next) => {
senseChange()
.then(data =>{
res.send(data);
console.log(data);
})
})
function senseChange() {
return new Promise((resolve) => {
changeStream = db.errand.watch();
changeStream.on('change', data => {
console.log("Update done!");
resolve(data)
})
});
}
I keep getting a 404 when I am posting to a route. I am using MongoDB, express and React Native. I have created the Schema, actions and router.
The Schema is below:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Edible Schema
const EdiblesSchema = new Schema({
name: {
type: String,
required: true
},
price: {
type: String,
required: true
},
strength: {
type: String,
required: true
},
purchasedLocation: {
type: String,
required: true
},
effects: {
type: String,
required: true
},
strain: {
type: String,
required: true
},
});
module.exports = Edibles = mongoose.model("edibles", EdiblesSchema);
Then the post router is below:
const express = require("express");
const router = express.Router();
const keys = require("../../config/keys");
// Load edibles model
const Edibles = require("../../models/edibles");
// #route POST api/users/edibles
// #desc Add an edible to the users collection
// #access Public
router.post ('/edibles', (req, res) => {
if (res.status === 200) {
const newEdible = new Edibles({
name: req.body.name,
price: req.body.price,
strength: req.body.strength,
strain: req.body.strain,
purchasedLocation: req.body.purchasedLocation,
effects: req.body.effects,
})
} else {
return res.status(400).json({ email: "Thats not going to get you high" });
} newEdible
.save()
.then( edibles => res.json(edibles))
.catch(err => console.log(err))
});
module.exports = router;
Then the finale we have the handleSubmit to send the users info to the api endpoint.
const handleSubmit = (response) => {
console.log("EDIBLES", name, strength, price, effects, strain)
dispatch(setEdible(payload))
if (response === 200) {
axios
.post(edibleApi, payload)
console.log("PAYLOAD", edibleApi, payload, setEdible)
// navigation.navigate("Dashboard")
} else {
console.log("WRONG", edibleApi, payload, setEdible);
console.log("userEdibles", userEdibles)
}
}
I am really lost with this... Please help!
The issue was that I was using the wrong endpoint. I worked this out by using the express-list-routes by adding it to my server.js file.
const expressListRoutes = require('express-list-routes');
const router = express.Router();
console.log("Now we cooking with gas", expressListRoutes(app, { prefix: '/api/v1' })))
That console.log must be added to the console.log that indicates if your server is running or not....
please i need help with creating the update function in the assignmentsController, i want to be able to have a user create an assignment, then i can be able to create a quiz inside of the assignments and return it. for example this is what i want return after updating the assignment quiz section.
{ "quiz": [{question:""this is a sample question?", "correct_answer":"sample correct", "incorrect_answers: ["wrong", "not correct"], "createdAt": "2020-12-10T00:50:27.932Z", "_id": "5fd170d6712a647ad072c449", "title": "what are you?", }
This is the update function
export const updateAssignments = async (req, res) => {
const { id } = req.params;
const {title} = req.body;
if (!mongoose.Types.ObjectId.isValid(id)) return res.status(404).send(`No Asssignment with id: ${id}`);
const updatedPost = {title,_id: id, $push: { quiz:[{$each: updatedquiz} ]}};
// await Assignment.findByIdAndUpdate(assignmentId)
await Assignments.findByIdAndUpdate(id, updatedPost, { new: true });
res.json(updatedPost);
}
these are all the files
**Assignment.js**
import mongoose from 'mongoose'
const AssignmentsSchema = new mongoose.Schema({
title: String,
quiz: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Quiz"
}],
createdAt: {
type: Date,
default: new Date(),
},
});
const Assignments = mongoose.model("Assignments", AssignmentsSchema)
export default Assignments;
`
- **Quiz.js**
import mongoose from 'mongoose';
const QuizSchema = mongoose.Schema({
question: String,
correct_answer: String,
incorrect_answers: [],
assignments: {
type: mongoose.Schema.Types.ObjectId,
ref: "Assignments"
},
})
var Quiz = mongoose.model('Quiz', QuizSchema);
export default Quiz;
**AssignmentsController.js**
import express from 'express';
import mongoose from 'mongoose';
import Assignments from '../models/Assignments.js';
import Assignment from '../models/Quiz.js';
const router = express.Router();
export const getAssignments = async (req, res) => {
try {
const postAssignment = await Assignments.find().populate('quiz');
res.status(200).json(postAssignment);
} catch (error) {
res.status(404).json({ message: error.message });
}
}
export const getAssignmentsById = async (req, res) => {
const { id } = req.params.id;
try {
const post = await (await Assignments.findById(id)).populate('quiz');
res.status(200).json(post);
} catch (error) {
res.status(404).json({ message: error.message });
}
}
export const createAssignments = async (req, res) => {
try {
const { title, createdAt} = req.body;
const newAssignment = new Assignments({
title,
createdAt,
quiz: [req._id],
});
await newAssignment
.populate('quiz')
.execPopulate()
// newAssignment.assignmentQuestion = newAssignment.assignment.question
// newAssignment.assignmentDate = createdAt
// newAssignment.correctanswer = registration.user.email
newAssignment.save()
res.status(201).json(newAssignment );
} catch (error) {
res.status(409).json({ message: 'does not work' });
}
}
export const updateAssignments = async (req, res) => {
const { id } = req.params;
// const { quizid } = req.params;
// const { question, correct_answer, incorrect_answers} = req.body;
const {title} = req.body;
if (!mongoose.Types.ObjectId.isValid(id)) return res.status(404).send(`No Asssignment with id: ${id}`);
const updatedPost = {title,_id: id, $push: { quiz:[{$each: updatedquiz} ]}};
// await Assignment.findByIdAndUpdate(assignmentId)
await Assignments.findByIdAndUpdate(id, updatedPost, { new: true });
res.json(updatedPost);
}
export const deleteAssignment = async (req, res) => {
const { id } = req.params;
if (!mongoose.Types.ObjectId.isValid(id)) return res.status(404).send(`No Assignment with id: ${id}`);
await Assignment.findByIdAndRemove(id);
res.json({ message: "Assignment deleted successfully." });
}
export default router;
**assignmentsRoute.js**
import express from 'express';
import { createAssignments, getAssignments, getAssignmentsById, updateAssignments } from '../controllers/AssignmentsController.js';
const router = express.Router();
//Assignment
router.get('/', getAssignments);
router.post('/', createAssignments);
router.get('/:assignment_id', getAssignmentsById);
router.patch('/:assignment_id/quiz', updateAssignments);
router.delete('/:assignment_id', deleteAssignment);
export default router;
**server.js**
import express from 'express'
import bodyParser from 'body-parser'
import mongoose from 'mongoose'
import cors from 'cors'
import dotenv from 'dotenv'
import userRoutes from './routes/userRoute.js';
import quizRoutes from './routes/quizRoute.js'
import assignmentsRoutes from './routes/assignmentsRoute.js';
import loginRoutes from './routes/loginRoute.js';
import registrationRoutes from './routes/registrationRoute.js';
const app = express();
app.use(cors());
const PORT = process.env.PORT || 8001;
if(process.env.NODE_ENV !== 'production'){
dotenv.config()
}
app.use(bodyParser.json()) // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true }))
app.use('/user', userRoutes);
app.use('/login', loginRoutes);
app.use('/registration', registrationRoutes);
app.use('/quiz', quizRoutes);
app.use('/assignments', assignmentsRoutes);
mongoose.connect(process.env.MONGO_DB_CONNECTION, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => app.listen(PORT, () => console.log(`Server Running on Port: http://localhost:${PORT}`)))
.catch((error) => console.log(`${error} did not connect`));
what i initially wanted was to create an assignment and then add quiz questions in it, in order to do that i needed to change the model schema of the Assignment model to have an array of quizzes instead of it referencing a model of Quiz. then i performed the $push method and so i can add as many questions as i want.
Assignments.js
import mongoose from 'mongoose'
const AssignmentsSchema = new mongoose.Schema({
title: String,
quizes: [{
question:String,
correct_answer:String,
incorrect_answers:[]
}],
createdAt: {
type: Date,
default: new Date(),
},
});
const Assignments = mongoose.model("Assignments", AssignmentsSchema)
export default Assignments;
then i created the addQuestion function in AssignmentController.js
`export const addQuestion = async (req, res) =>{
const { id } = req.params;
try {
const addedQuestion = await Assignments.findByIdAndUpdate(
{_id: id},
{ $push: { quizes: {$each: req.body.quizes}}},
{safe: true, upsert: true, new : true}
);`
this is the result
{
_id:5fd83417c78f8dd70351c613
createdAt:2020-12-15T03:53:17.724+00:00
title:"first assignment"
quizes:Array
{0:Object
incorrect_answers:Array
{
0:"wrong"
1:"write"
2:"ugly"
}
_id:5fd83593106af1d8fa87b94c
question:"this is question 1"
correct_answer:"sample answer"
{
1:Object
incorrect_answers:Array
_id:5fd835a3106af1d8fa87b94d
question:"this is question 2"
correct_answer:"sample answer 2"
{
2:Object
incorrect_answers:Array
_id:5fd835ba106af1d8fa87b94e
question:"this is question 3"
correct_answer:"sample answer 3"
}
}
}
I am trying to create a sample API of restaurants using POST but after starting API and loading it into Postman it does not show results.
router.js
const express = require('express');
const restaurantController = require('../Controllers/restaurantData');
const router = express.Router();
router.post('/restaurantFilter',(req, res) => {
restaurantController.getfilter
});
module.exports = router;
app.js
const express = require('express');
const bodyparser = require('body-parser');
const mongoose = require('mongoose');
const apiRouter = require('./Routes/router');
const port = 4005;
const app = express();
app.use(bodyparser.json());
app.use('/api', apiRouter);
mongoose.connect(
'mongodb://127.0.0.1:27017/sample',
{ useNewUrlParser: true, useUnifiedTopology: true }
).then(success => {
console.log('Connected to MongoDB');
app.listen(port, () => {
console.log(`Server started at port ${port}`);
});
}).catch(error => {
console.log(error);
});
restaurant.js (Controller)
const restaurants = require('../Models/restaurantData');
exports.getfilter = (req, res) => {
const city_name = req.body.city_name;
const cost = req.body.cost;
restaurants.find({
city_name: city_name,
cost: cost
}).then(result => {
res.status(200).json({
message: "Filtered Data",
result
})
}).catch(error => {
res.status(500).json({
message: error
})
})
}
restaurantData.js (Model)
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const restaurantSchema = new Schema({
name: {
type: String,
required: true
},
city_name:{
type: String,
required: true
},
city: {
type: Number,
required: true
},
area: {
type: Number,
required: true
},
locality:{
type: String,
required: true
},
thumb: {
type: String,
required: true
},
cost:{
type: Number,
required: true
},
address:{
type: String,
required: true
},
mealtype:{
type: Number,
required: true
},
name:{
type: String,
required: true
},
cuisine:{
type: Number,
required: true
},
type:{
type: Array,
required: true
},
Cuisine:{
type: Array,
required: true
}
});
module.exports = mongoose.model('restaurantData', restaurantSchema, 'restaurantData');
I think mostly it is the router problem but trying to know where? So, share any ideas. Thank You.
This request handler:
router.post('/restaurantFilter',(req, res) => {
restaurantController.getfilter
});
Does not actually call the getfilter function so nothing is ever sent from the POST request. You can fix that by either doing this:
router.post('/restaurantFilter', restaurantController.getfilter);
or this:
router.post('/restaurantFilter',(req, res) => {
restaurantController.getfilter(req, res);
});
Then, it looks like you also have to property export and import that getfilter() function. You appear to export it just fine in restaurant.js:
exports.getfilter = (req, res) => { ... });
But, you don't seem to be importing the controller properly as you're doing this:
const restaurantController = require('../Controllers/restaurantData');
When it looks like you should be doing this:
const restaurantController = require('../Controllers/restaurant.js');
so that you're assigning the controller the object that actually has the getfilter method on it.
Well, I'm trying to get a value of property from a object with Mongoose find(), but for some reason, the mongoose are returning a undefined value.
The Schema:
const mongoose = require('mongoose');
const uuid = require('uuid');
const Schema = mongoose.Schema({
dsID: { type: String, unique: true, require: true },
dsTag: { type: String },
mcCode: { type: String, default: () => uuid.v4(), unique: true, select: false },
mcConnected: { type: Boolean, default: false }
}, { versionKey: false });
const Members = mongoose.model("Members", Schema);
module.exports = Members;
The code
// Database connection
mongoose.connect(DATABASE.uri, DATABASE.options);
Members.find({ 'dsID': dsID }, (err, member) => {
const connected = member.mcConnected;
console.log(connected)
});
This might be because of you should not name a model 'Schema'. Try with other name because "Schema" is reserved word
Use this code on schema
const mongoose = require('mongoose');
const uuid = require('uuid');
const memberSchema = new mongoose.Schema({
dsID: { type: String, unique: true, require: true },
dsTag: { type: String },
mcCode: { type: String, default: () => uuid.v4(), unique: true, select: false },
mcConnected: { type: Boolean, default: false }
}, { versionKey: false });
const Members = mongoose.model("Members", memberSchema);
module.exports = Members;
Here u go boys:
const app = express()
const port = 3000
//MongoDB Connection
const DB_Connect = require('./(8.1)MongoDB_Connection')
const DB = DB_Connect() //returning a Model
//Middleware
const logger = function(req, res, next) {
console.log('logging')
next()
}
app.use(logger)
//Routes
app.get('/', async(req, res) => {
console.log(DB.then((docs) => {
console.log(docs.find({ name: 'POCO X3 Pro' }, (error, docs) => {
if (error) {
console.log("Error: " + error)
} else {
console.log(docs)
}
}))
}))
})
/*
DB is a Model and console.log(DB) gives : " Promise { Model { users } } ".
But for Promise we use .then() for result.
Model { users }
As we use .find(), we got the answer
*/
//Listening
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
//Muhammad Irtaza Ghaffar (Pakistan)
Thanks me later!