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"
}
}
}
Related
I've noticed that in my application, some pages show a status code 304 whereas some other ones show a status code 200.
Besides that, there is a page that is not displaying on production mode and shows a status code 502.
Why there is such differences in my application for the pages that are working, but showing a status code 304 and 200?
Moreover, why my blog page is not displaying on production mode and shows the status code 502 and displays the following message:
Incomplete response received from application
Though, the blog page is displaying well on development mode and shows the status code 304.
Is there any relation between the status code 304 in development and the status code 502 in production mode?
I mean, the status code 304 in development mode could be the reason for the error and the status code 502 in production mode?
Below is my code.
app.js:
const path = require('path');
const express = require('express');
const session = require('express-session');
const sessionConfig = require('./config/session');
const db = require('./data/database');
const adminRoutes = require('./routes/admin/blog');
const authRoutes = require('./routes/admin/auth');
const defaultRoutes = require('./routes/home/default');
const postsRoutes = require('./routes/home/posts');
const quotationsRoutes = require('./routes/home/quotations');
const contactsRoutes = require('./routes/home/contacts');
const authMiddleware = require('./middlewares/auth-middleware');
const mongoDbSessionStore = sessionConfig.createSessionStore(session);
let port = 3000;
if (process.env.MONGODB_URL) {
port = process.env.MONGODB_URL;
}
const app = express();
app.set('views', [
path.join(__dirname, 'views/home'),
path.join(__dirname, 'views/admin')
]);
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use('/public/admin/images', express.static('public/admin/images'));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(session(sessionConfig.createSessionConfig(mongoDbSessionStore)));
app.use(authMiddleware);
app.use('/', adminRoutes);
app.use('/', authRoutes);
app.use('/', defaultRoutes);
app.use('/', postsRoutes);
app.use('/', quotationsRoutes);
app.use('/', contactsRoutes);
app.use(function (req, res) {
res.status(404).render('404');
});
app.use(function (error, req, res, next) {
console.error(error);
res.status(500).render('500');
});
db.connectToDatabase()
.then(function () {
app.listen(port);
})
.catch(function (error) {
console.log('La connexion à la base de données a échoué !');
});
routes\home\posts.js:
const express = require('express');
const mongodb = require('mongodb');
const xss = require('xss');
// const uuid = require('uuid');
const db = require('../../data/database');
const blogControllers = require('../../controllers/post-controllers');
const router = express.Router();
router.get('/blog', blogControllers.getBlog);
router.get('/blog/:id', blogControllers.getBlogId);
router.get('/blog/:id/comments', blogControllers.getBlogIdComments);
router.post('/blog/:id/comments', blogControllers.postBlogIdComments);
router.get('/profile', blogControllers.getProfile);
module.exports = router;
routes\admin\blog.js:
const express = require('express');
const multer = require('multer');
const storageConfig = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/admin/images');
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname);
}
});
const upload = multer({ storage: storageConfig });
const blogControllers = require('../../controllers/post-controllers');
const router = express.Router();
router.get('/posts', blogControllers.getPosts);
router.get('/new-post', blogControllers.getNewPost);
router.post('/new-post', upload.single('image'), blogControllers.postNewPost);
router.get('/blog/:id/edit', blogControllers.getBlodIdEdit);
router.post('/blog/:id/edit', blogControllers.postBlogIdEdit);
router.post('/blog/:id/delete', blogControllers.postBlogIdDelete);
router.get('/admin', blogControllers.getAdmin);
module.exports = router;
models\post.js:
const mongodb = require('mongodb');
const db = require('../data/database');
const ObjectId = mongodb.ObjectId;
class Post {
constructor(title, summary, content, date, author, image, id) {
this.title = title;
this.summary = summary;
this.content = content;
this.date = date;
this.author = author;
this.image = image;
if (id) {
this.id = new ObjectId(id);
}
}
static async fetchAll() {
const posts = await db
.getDb()
.collection('posts')
.find({})
.project({ title: 1, summary: 1, content: 1, 'author.name': 1 })
.toArray();
return posts;
}
async fetch() {
if (!this.id) {
return;
}
const postDocument = await db
.getDb()
.collection('posts')
.findOne(
{ _id: new ObjectId(this.id) },
{ title: 1, summary: 1, content: 1 }
);
this.title = postDocument.title;
this.summary = postDocument.summary;
this.content = postDocument.content;
}
async save() {
let result;
if (this.id) {
result = await db
.getDb()
.collection('posts')
.updateOne(
{ _id: this.id },
{
$set: {
title: this.title,
summary: this.summary,
content: this.content
}
}
);
} else {
result = await db.getDb().collection('posts').insertOne({
title: this.title,
summary: this.summary,
content: this.content,
date: this.date,
author: this.author,
imagePath: this.image
});
}
return result;
}
async delete() {
if (!this.id) {
return;
}
const result = await db
.getDb()
.collection('posts')
.deleteOne({ _id: this.id });
return result;
}
}
module.exports = Post;
controllers\post-controllers.js:
const mongodb = require('mongodb');
const db = require('../data/database');
const Post = require('../models/post');
const ObjectId = mongodb.ObjectId;
async function getBlog(req, res) {
const posts = await db
.getDb()
.collection('posts')
.find({})
.project({
title: 1,
summary: 1,
content: 1,
'author.name': 1,
imagePath: 1
})
.toArray();
console.log(posts);
res.render('posts', { posts: posts });
}
async function getBlogId(req, res, next) {
let postId = req.params.id;
try {
postId = new ObjectId(postId);
} catch (error) {
return res.status(404).render('404');
// return next(error);
}
const post = await db
.getDb()
.collection('posts')
.findOne({ _id: postId }, { summary: 0 });
if (!post) {
return res.status(404).render('404');
}
post.humanReadableDate = post.date.toLocaleDateString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
});
post.date = post.date.toISOString();
res.render('post-detail', { post: post, comments: null });
}
async function getBlogIdComments(req, res) {
const postId = new ObjectId(req.params.id);
const comments = await db
.getDb()
.collection('comments')
.find({ postId: postId })
.toArray();
res.json(comments);
}
async function postBlogIdComments(req, res) {
const postId = new ObjectId(req.params.id);
const newComment = {
postId: postId,
title: xss(req.body.title),
text: xss(req.body.text)
};
await db.getDb().collection('comments').insertOne(newComment);
res.json({ message: 'Commentaire ajouté !' });
// res.status(500).json({ message: 'Error!' });
}
function getProfile(req, res) {
if (!res.locals.isAuth) {
// if (!req.session.user)
return res.status(401).render('401');
}
res.render('profile');
}
async function getPosts(req, res) {
const posts = await Post.fetchAll();
res.render('posts-list', { posts: posts });
}
async function getNewPost(req, res) {
const authors = await db.getDb().collection('authors').find().toArray();
res.render('create-post', { authors: authors });
}
async function postNewPost(req, res) {
const uploadedImageFile = req.file;
const authorId = new ObjectId(req.body.author);
const author = await db
.getDb()
.collection('authors')
.findOne({ _id: authorId });
const enteredTitle = req.body.title;
const enteredSummary = req.body.summary;
const enteredContent = req.body.content;
const date = new Date();
const selectedAuthor = {
author: {
id: authorId,
name: author.name,
email: author.email
}
};
const selectedImage = uploadedImageFile.path;
const post = new Post(
enteredTitle,
enteredSummary,
enteredContent,
date,
selectedAuthor.author,
selectedImage
);
await post.save();
res.redirect('/posts');
}
async function getBlodIdEdit(req, res) {
const post = new Post(null, null, null, null, null, null, req.params.id);
await post.fetch();
if (!post.title || !post.summary || !post.content) {
return res.status(404).render('404');
}
res.render('update-post', { post: post });
}
async function postBlogIdEdit(req, res) {
const enteredTitle = req.body.title;
const enteredSummary = req.body.summary;
const enteredContent = req.body.content;
const post = new Post(
enteredTitle,
enteredSummary,
enteredContent,
...[, , ,], // pass 3 undefined arguments
req.params.id
);
await post.save();
res.redirect('/posts');
}
async function postBlogIdDelete(req, res) {
const post = new Post(null, null, null, null, null, null, req.params.id);
await post.delete();
res.redirect('/posts');
}
async function getAdmin(req, res) {
if (!res.locals.isAuth) {
// if (!req.session.user)
return res.status(401).render('401');
}
if (!res.locals.isAdmin) {
return res.status(403).render('403');
}
res.render('admin');
}
module.exports = {
getBlog: getBlog,
getBlogId: getBlogId,
getBlogIdComments: getBlogIdComments,
postBlogIdComments: postBlogIdComments,
getProfile: getProfile,
getPosts: getPosts,
getNewPost: getNewPost,
postNewPost: postNewPost,
getBlodIdEdit: getBlodIdEdit,
postBlogIdEdit: postBlogIdEdit,
postBlogIdDelete: postBlogIdDelete,
getAdmin: getAdmin
};
Its my first time trying to do a POST request with Postman using Koa in my application. I have the router and the body parser but for some reason i still get an error message sayng that my request body is undefined. I think the body parser is not working but i have no idea why.
routes.js
const Koa = require('koa');
const bodyParser = require('koa-body')
const Router = require('koa-router')
const app = new Koa()
const router = new Router()
const Topic = require('./models/topic')
router.post('/topics', bodyParser(), async (ctx) => {
console.log(JSON.stringify(ctx.request.body))
const { name } = ctx.request.body
newPost = {
name: {name}
}
let newTopic = new Topic(newPost)
await newTopic.save(function(error, newPost){
if (error) {
console.log(error)
} else {
res.status(201).json({
message : 'Name added!'
}).send(newPost)
}
})
return
})
app
.use(router.allowedMethods())
.use(router.routes())
module.exports = router
topic.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const TopicSchema = new Schema(
{
name: {type: String, required: true },
viewCount: {type: Number, default: 0 }
},
{
timestamps: true
}
)
module.exports = mongoose.model('two/Topic', TopicSchema)
Error message:
{}
Error: two/Topic validation failed: name: Cast to string failed for value "{ name: undefined }" at path "name"
at ValidationError.inspect (/home/node/app/node_modules/mongoose/lib/error/validation.js:47:26) ...
EDIT
Also adding in server.js for further reference
const Koa = require('koa');
const mongoose = require('mongoose');
const router = require('./routes');
const app = new Koa();
app.use(require('koa-body')());
app.use(router.routes());
mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
const listener = app.listen(process.env.APP_PORT || 3000, () =>
console.log('App started on port ' + listener.address().port)
)
})
.catch((error) => {
console.log(error)
process.exit(1)
})
// app.proxy = true;
module.exports = app;
I try to fetch an API and save the data to MongoDB, but i think i have some problem with my POST method..
I would like to store the data what i fetch from the API and then if i change data in the front i would like if it changed in the database
Here is my code snippet:
App.js file
class App extends React.Component {
state = {
name: "",
movie: [],
};
componentDidMount = () => {
this.getMovie();
this.displayMovie();
};
getMovie = () => {
axios.get("http://api.tvmaze.com/shows?page=1").then((response) => {
const data = response.data;
this.setState({
movie: data,
});
console.log("Data has been received");
console.log(this.state.movie);
});
};
displayMovie = () => {
axios({
url: "/",
method: "POST",
data: this.state.movie,
})
.then(() => {
console.log("Data has been sent to the server");
this.getMovie();
})
.catch((err) => {
console.log(err);
console.log("Internal server error");
});
};
render() {
return (
<div>
<form onSubmit={this.displayMovie}>
<button type="submit">Send</button>
<h2>Movie List</h2>
<div>
{this.state.movie.map((t) => {
return <p>{t.name}</p>;
})}
</div>
</form>
</div>
);
}
}
export default App;
server.js file
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const app = express();
const movieRouter = require("./routes/movie.routes");
const connect = () => {
return mongoose
.connect("mongodb://localhost:27017/movie", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("db connected"))
.catch((err) => console.log(err));
};
connect();
app.use(express.json());
app.use("/", movieRouter);
app.use(bodyParser.json({ limit: "50mb", extended: true }));
app.use(bodyParser.urlencoded({ limit: "50mb", extended: true }));
app.listen(5000, () => {
console.log("app is running on 5000");
});
model Schema
const mongoose = require("mongoose");
const movieSchema = new mongoose.Schema({
name: {
type: String,
},
});
const MovieSchema = mongoose.model("movieSchema", movieSchema);
module.exports = MovieSchema;
service js file
const MovieSchema = require("../models/movie.models");
const getMovie = async () => {
const movie = await MovieSchema.find();
return movie;
};
module.exports = {
getMovie,
};
controller file
const getMovie = async (req, res, next) => {
try {
const movie = await movieService.getMovie();
res.status(200).json({ result: movie });
} catch (err) {
next(err);
}
};
module.exports = {
getMovie,
};
router file
const express = require("express");
const router = express.Router();
const movieController = require("../controllers/movie.controllers");
router.get("/", movieController.getMovie);
module.exports = router;
What am i doing wrong ? I have POST http://localhost:3000/ 404 (Not Found) error message.
Thank you for help!
First of all your POST route handler is missing (ref: Andrew Nolan).
Secondly your react code App.js componentDidMount method is calling getMovie and straight after calling displayMovie. It has to wait till getMovie method returns the results. So i placed promises to solve it.
class App extends React.Component {
state = {
name: "",
movie: [],
};
async componentDidMount() {
try {
await this.getMovie();
this.displayMovie();
} catch (e) {
console.log(e);
}
};
getMovie = async () => {
return new Promise((resolve, reject) => {
axios.get("http://api.tvmaze.com/shows?page=1").then(({ data }) => {
this.setState({
movie: data,
});
resolve();
}).catch(e => reject(e));
});
};
displayMovie = async () => {
axios({
url: "/",
method: "POST",
data: this.state.movie,
})
.then(() => this.fetchMovie())
.catch((err) => console.log(err));
};
render() {
return (
<div>
<form onSubmit={this.displayMovie}>
<button type="submit">Send</button>
<h2>Movie List</h2>
<div>
{this.state.movie.map((t) => {
return <p>{t.name}</p>;
})}
</div>
</form>
</div>
);
}
}
export default App;
You don't need to send status code 200. json method will stringify the json object and attach 200 status code as default.
res.status(200).json({ result: movie }); // too long
res.json({ result: movie }); // better practice
res.json({ movie }); // even better
When you are creating mongoose schema, you don't need to explicitly declare type of the data in object literals unless you want to add other configurations.
const movieSchema = new mongoose.Schema({
name: {
type: String,
},
});
const movieSchema = new mongoose.Schema({
name: String // better
});
In your code, you have only specified a GET route for /. You also need to specify a POST route too.
const express = require("express");
const router = express.Router();
const movieController = require("../controllers/movie.controllers");
router.get("/", movieController.getMovie);
router.post("/", movieController.saveMovie);
module.exports = router;
I put in movieController.saveMovie as a placeholder for whatever gets invoked at this route. That part is up to you. I didn't see a method for it in your code snippets to save it.
You are also missing post controller
just like get, add post controller in controller file too.
const postMovie = async (req, res, next) => {
const {name} = req.body;
try {
const newMovie = new Movie({
name,
});
const movie = await newMovie.save();
res.status(200).json({ result: movie });
} catch (err) {
next(err);
}
};
module.exports = {
postMovie,
};
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.
I am sending request from form (using Angularjs) to create new user. It works and inserts data in my collection. But how i manage to update my data on backend part using node js express. For example i want to check if username is free. I am trying to console.log something when i send post request. But nothing is logging.
Here is my server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const restify = require('express-restify-mongoose');
//const userRep = require('./front/core/repository/user/user.repository');
// Middleware
const head = require('./back/midleware/headers.config');
// Models
// TODO provide schema when it will be raedy
const userModel = require('./back/models/user.model');
const app = express();
const router = express.Router();
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/users');
// Body parser config
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Headers config
app.use(head.headerConfig);
// Endpoint configuration
restify.serve(router, userModel.UserModel, {
name: 'users',
});
app.use(router);
app.post('/users', (req, res) => {
console.log('req.post')
})
app.post('/users', (req, res) => {
console.log('req.post')
})
app.listen(2000, function () {
console.info('Server is locating on port 2000');
console.info('to access localhost:2000/api/v1');
});
Ajax Request:
import { UserRepository } from '../../core/repository/user/user.repository';
import * as _ from 'lodash';
class HttpExampleController {
constructor(UserRepository) {
this.repository = UserRepository;
this.allUsers = [];
this.user = {};
this.newUser = {
id: 4,
email: "new#email.com",
username: "newUserName",
name: "newName"
};
this.updatedUser = {
email: "updated#email.com",
name: "updatedUserName"
};
this.getAllUsers();
}
getAllUsers() {
this.repository.getAllUsers()
.then(userList => {
this.allUsers = userList;
});
}
// Discuss if we need this method
getUser(userId) {
this.repository.getUser(userId)
.then(user => {
this.user = user;
});
}
createUser(user) {
this.repository.createUser(user)
.then(res => {
this.allUsers.push(res);
});
}
updateUser(user, data) {
let index = _.indexOf(this.allUsers, _.find(this.allUsers, findUser => findUser._id === user._id));
this.repository.updateUser(user._id, data)
.then(res => {
this.allUsers[index] = res;
});
}
deleteUser(user) {
let index = _.indexOf(this.allUsers, _.find(this.allUsers, findUser => findUser._id === user._id));
this.repository.deleteItem(user._id)
.then(res => _.pull(this.allUsers, res));
}
testFunc() {
this.allUsers.shift();
}
}
export { HttpExampleController };