How to get MongoDB data to select option using NodeJS - node.js

I am trying to populate MongoDB data to html select option.
This is what I have done so far
I have created a database books and created collection AuthorDB
I manually inserted data (to check if it really is working)
But when I used postman to get data, I get an empty array means no data. (But I have inserted data to AuthorDB collection)
Here is my server.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const BookDB = require('./book-dbmodel');
const AuthorDB = require('./author-dbmodel');
const app = express();
const router = express.Router();
app.use(bodyParser.json());
app.use(cors());
app.use('/books', router);
//connect to books database
mongoose.connect('mongodb://127.0.0.1:27017/books', {useNewUrlParser: true});
const connection = mongoose.connection;
connection.once('open', () => {
console.log("Connected to MongoDB via port 27017");
});
app.listen(4000, () => {
console.log('Listening to port 4000');
});
// add book http://localhost:4000/books/add
router.route('/add').post((req, res) => {
let bookDB = new BookDB(req.body);
bookDB.save().then((bookDB) => {
res.status(200).send(`${bookDB} Added!`);
}).catch((err) => {
res.status(400).send({message: err});
});
});
//get all authors http://localhost:4000/books/authors
router.route('/authors').get((req, res) => {
AuthorDB.find((err, authors) => {
if(err) throw err;
res.status(200).send(authors);
});
});
//get books by author name http://localhost:4000/books/authors/authorName
router.route('/authors/authorName').get((req, res) => {
let authorName = req.params.authorName;
BookDB.find({firstName: {$regex: `${authorName}`, $options: "i"}}, (err, books) => {
if(err) throw err;
res.status(200).send(books);
});
});
And this is my App.js in front-end:
import React, {Component} from 'react';
import axios from 'axios';
const ShowAuthors = (props) => (
<option value={props.author.firstName}>{props.author.firstName}</option>
);
export default class AddBooks extends Component{
constructor(props){
super(props);
this.state = {
authorArray: [],
name: '',
isbn: 0,
author: '',
price: 0,
yearOfPublication: 0,
publisher: ''
}
}
//to get author list on dropdown select
componentDidMount(){
axios.get('http://localhost:4000/books/authors/')
.then(authors => {
console.log(authors.data);
this.setState({
authorArray: authors.data
});
}).catch(err => {
console.log(err);
});
}
getAuthors(){
return this.state.authorArray.map((currentAuthor, id) => {
return <ShowAuthors author={currentAuthor} key={id} />
});
}
onSubmit(){
}
onChangeName(){
}
onChangeISBN(){
}
render(){
return(
<div className="container">
<h1>Add Books</h1>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label htmlFor="book-name">Book Name</label>
<input
value={this.state.name}
onChange={this.onChangeName}
type="text" className="form-control" id="book-name" aria-describedby="emailHelp" placeholder="Book Name"/>
</div>
<div className="form-group">
<label htmlFor="book-isbn">ISBN</label>
<input
value={this.state.isbn}
onChange={this.onChangeISBN}
type="number" className="form-control" id="book-isbn" aria-describedby="emailHelp" placeholder="ISBN"/>
</div>
<div className="form-group">
<label htmlFor="author-name">Authors</label>
<select
className="form-control" name="authors" id="authors">
{this.getAuthors()} {/* this doesn't return anything but an empty array */}
</select>
</div>
<div className="form-group">
<label htmlFor="book-price">Book Price</label>
<input type="number" className="form-control" id="book-price" name="book-price" aria-describedby="emailHelp" placeholder="Book Price"/>
</div>
<div className="form-group">
<label htmlFor="book-year">Published Year</label>
<input type="number" className="form-control" id="book-year" name="book-year" aria-describedby="emailHelp" placeholder="Year"/>
</div>
<div className="form-group">
<label htmlFor="book-publisher">Book Publisher</label>
<input type="number" className="form-control" id="book-publisher" name="book-publisher" aria-describedby="emailHelp" placeholder="Publisher"/>
</div>
</form>
</div>
);
}
}
And this is my mongodb visualization:
And this is my AuthorDB schema model:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let AuthorDB = new Schema({
firstName: {type: String},
lastName: {type: String},
nationality: {type: String}
});
module.exports = mongoose.model('AuthorDB', AuthorDB);

for mongoose.model() method
The first argument is the singular name of the collection your model
is for. Mongoose automatically looks for the plural, lowercased
version of your model name. Thus, for the example above, the model
Tank is for the tanks collection in the database.
Mongoose trying to be smart and detect the model name, but you can force it to use the collection you want like this:
new Schema({..}, { collection: 'AuthorDB' })
Or when you create the model, like this:
module.exports = mongoose.model('AuthorDB', AuthorDB, 'AuthorDB')
Also you're trying to access this parameter req.params.authorName while it not defined in your route, you're missing : in your route.
router.route('/authors/authorName')
It should be like this:
router.route('/authors/:authorName')
to be able to get the authorName value.

Related

My app crashed when I am trying to add product from react by using multer?

My app crash when I like on submit button on my react app but when I comment my image code then no problem comes and its enter the other info int mongodb so there is issue in my handlesubmit code there is something missing for image because my backend node.js code work and its enter the image in the databae .I used multer for sending the image.
Here is my react code
Productstate.js
import React, { useState } from 'react'
import Productcontext from './Productcontext'
const Prductstate = (props) => {
const host = "http://localhost:5000"
const productInitial = []
const [product, setProduct] = useState(productInitial);
//Add Note
const addProduct = async (title, description, price, category, image) => {
//TODO API CALL
let url = `${host}/api/product/upload`
//Api Call
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
headers: {
'Content-Type': 'application/json',
'auth-token': "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjoiNjJlZThmMGI4NmU1YzQ5NDZkM2I3NWQ1In0sImlhdCI6MTY1OTgwMTM1NX0.NdR38S1oby9mSzl1zTH-LYYavsJGjwq6OWsPP_q3YvI"
},
body: JSON.stringify({ title, description, price, category, image }) // body data type must match "Content-Type" header
});
const json = response.json(); // parses JSON response into native JavaScript objects
console.log("adding a new note");
const newpro = {
"_id": "63304097cc95e936a974bd6e",
"user": "62ee8f0b86e5c4946d3b75d5",
"title": title,
"description": description,
"price": price,
"category": category,
"image":{
"data":"BinData(0, 'bG9nc2lnbi5wbmc=')",
"contentType":"image/png "
},
"date": "2022-08-25T10:26:57.324Z",
"__v": 0
}
setProduct(product.concat(newpro));
}
//logic to add a note
return (
<Productcontext.Provider value={{ product, addProduct }}>
{props.children}
</Productcontext.Provider>
)
}
export default Prductstate
Adminform.js
import React,{useContext,useState} from 'react'
import Productcontext from '../context/Productcontext';
const Adminform = () => {
const context=useContext(Productcontext);
const {addProduct}=context;
const handleClick=(e)=>{
e.preventDefault();
addProduct(product.title,product.description,product.price,product.category,product.image);
}
const onChange=(e)=>{
setProduct({...product,[e.target.name]:e.target.value})
}
const [product, setProduct] = useState({title:"",description:"",price:"",category:"",image:""})
return (
<div className="container">
<div className="screen">
<div className="screen__content">
<form className="login" encType="multipart/form-data" onSubmit={handleClick}>
<div className="login__field">
<i className="login__icon fas fa-user"></i>
<input type="text" className="login__input" placeholder="Name of Product" name='title' onChange={onChange}/>
</div>
<div className="login__field">
<i className="login__icon fas fa-lock"></i>
<input type="text" className="login__input" placeholder="Description" name='description' onChange={onChange}/>
</div>
<div className="login__field">
<i className="login__icon fas fa-lock"></i>
<input type="text" className="login__input" placeholder="Price" name='price' onChange={onChange}/>
</div>
<div className="login__field">
<i className="login__icon fas fa-lock"></i>
<input type="text" className="login__input" placeholder="Category" name='category' onChange={onChange}/>
</div>
<div className="login__field">
<i className="login__icon fas fa-lock"></i>
<input type="file" className="login__input" name="uploaded_file" onChange={onChange}/>
</div>
<button className="button login__submit">
<span className="button__text">Add Product</span>
<i className="button__icon fas fa-chevron-right"></i>
</button>
</form>
<div className="social-login">
<h3></h3>
<div className="social-icons">
</div>
</div>
</div>
<div className="screen__background">
<span className="screen__background__shape screen__background__shape4"></span>
<span className="screen__background__shape screen__background__shape3"></span>
<span className="screen__background__shape screen__background__shape2"></span>
<span className="screen__background__shape screen__background__shape1"></span>
</div>
</div>
</div>
)
}
export default Adminform
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
My backend code
ProductModel.js
const mongoose = require('mongoose');
const { Schema } = mongoose;
const ProductSchema = new Schema({
user:{
type:mongoose.Schema.Types.ObjectId,
ref:'user'
},
title:{
type:String,
required:true
},
description: {
type: String,
required: [true, "Please write description of product"]
},
price: {
type: Number,
required: [true, "Please Enter the Price"],
maxLength: [15, "Price cannot exceed 8 figure amount"]
},
category: {
type: String,
required: [true, "Category is must"]
},
image:{
data:Buffer,
contentType:String
}
});
const product=mongoose.model('product',ProductSchema);
module.exports=product;
Product.js
const express = require('express');
const { body, validationResult } = require('express-validator');
const router = express.Router();
const multer=require('multer');
const fetchuser = require('../middleware/fetchuser');
const productModel=require('../models/productModel');
const app = express()
//storage
const storage = multer.diskStorage({
destination: 'uploads',
filename: function (req, file, cb) {
cb(null,file.originalname)
}
})
const upload = multer({ storage: storage }).single('testImage');
router.post('/upload',fetchuser,async(req,res)=>{
upload(req,res,(err)=>{
if(err){
console.log(err);
}
else{
const newproduct= new productModel({
title:req.body.title,
description:req.body.description,
price:req.body.price,
category:req.body.category,
user: req.user.id,
image:{
data:req.file.filename,
contentType:'image/png '
}
})
newproduct.save()
.then(()=>res.send("succesfully uploaded")).catch((err)=>console.log(err))
}
})
});
module.exports=router;
index.js
const connectToMongo=require('./db');
var cors = require('cors');
const express = require('express')
connectToMongo();
const app = express()
app.use(cors())
const port = 5000
app.use(express.json());
app.use('/api/authent',require('./routes/authent'));
//app.use('/api/Categories',require('./routes/Categories'));
//app.use('/api/category',require('./routes/category'));
app.use('/api/product',require('./routes/product'));
app.listen(port, () => {
console.log(`ecart Backend listening on port ${port}`)
})

Why are my POST and PUT requests from Node/Express not working in React/Redux? My GET and DELETE requests all work fine. All requests work in Postman

So, I have the issue that everything works in Postman and my GET and DELETE requests even work in the full-stack program (Node/Express, React/Redux/Hooks, Microsoft SQL Server), but my POST and PUT requests are not working. As you can see in the image below, I have 403 errors and those lines are from "console.log(data);", not my error handler/catcher, so it is a "good" request, but something is not authorizing. Console logs and service file to show that data is passing, but not being accepted can be viewed here.
I have tried many, many solutions and much research. As far as I understand, this COULD be an issue with CORS, but I'm really not sure. Also, in Redux DevTools, it does not show my "UPDATE_DEVICE" OR "CREATE_DEVICE" actions, so I know that they are not even being accepted.
Here is code from AddDevice:
import { useDispatch } from "react-redux";
import { createDevice } from "../actions/devices";
const AddDevice = () => {
const initialDeviceState = {
id: null,
title: "",
detail: "",
published: false
};
const [device, setDevice] = useState(initialDeviceState);
const [submitted, setSubmitted] = useState(false);
const dispatch = useDispatch();
const handleInputChange = event => {
const { name, value } = event.target;
setDevice({ ...device, [name]: value });
};
const saveDevice = () => {
const { title, detail } = device;
dispatch(createDevice(title, detail))
.then(data => {
setDevice({
id: data.id,
title: data.title,
detail: data.detail,
published: data.published
});
setSubmitted(true);
console.log(data);
})
.catch(e => {
console.log(e);
});
};
const newDevice = () => {
setDevice(initialDeviceState);
setSubmitted(false);
};
return (
<div className="submit-form">
{submitted ? (
<div>
<h4>You submitted successfully!</h4>
<button className="btn btn-success" onClick={newDevice}>
Add
</button>
</div>
) : (
<div>
<div className="form-group">
<label htmlFor="title">Title</label>
<input
type="text"
className="form-control"
id="title"
required
value={device.title}
onChange={handleInputChange}
name="title"
/>
</div>
<div className="form-group">
<label htmlFor="detail">Detail</label>
<input
type="text"
className="form-control"
id="detail"
required
value={device.detail}
onChange={handleInputChange}
name="detail"
/>
</div>
<button onClick={saveDevice} className="btn btn-success">
Add
</button>
</div>
)}
</div>
);
};
export default AddDevice;
And here is from my code for updating the device:
useEffect(() => {
getDevice(props.match.params.id);
}, [props.match.params.id]);
const handleInputChange = event => {
const { name, value } = event.target;
setCurrentDevice({ ...currentDevice, [name]: value });
};
const updateStatus = status => {
const data = {
id: currentDevice.id,
title: currentDevice.title,
detail: currentDevice.detail,
published: status
};
dispatch(updateDevice(currentDevice.id, data))
.then(response => {
console.log(response);
setCurrentDevice({ ...currentDevice, published: status });
setMessage("The status was updated successfully!");
})
.catch(e => {
console.log(e);
});
};
const updateContent = () => {
dispatch(updateDevice(currentDevice.id, currentDevice))
.then(response => {
console.log(response);
setMessage("The device was updated successfully!");
props.history.push("/devices");
})
.catch(e => {
console.log(e);
});
};
const removeDevice = () => {
dispatch(deleteDevice(currentDevice.id))
.then(() => {
props.history.push("/devices");
})
.catch(e => {
console.log(e);
});
};
return (
<div>
{currentDevice ? (
<div className="edit-form">
<h4>Device</h4>
<form>
<div className="form-group">
<label htmlFor="title">Title</label>
<input
type="text"
className="form-control"
id="title"
name="title"
value={currentDevice.title}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="detail">Detail</label>
<input
type="text"
className="form-control"
id="detail"
name="detail"
value={currentDevice.detail}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label>
<strong>Status:</strong>
</label>
{currentDevice.published ? "Published" : "Pending"}
</div>
</form>
{currentDevice.published ? (
<button
className="m-3 btn btn-sm btn-danger"
onClick={() => updateStatus(false)}
>
UnPublish
</button>
) : (
<button
className="m-3 btn btn-sm btn-danger"
onClick={() => updateStatus(true)}
>
Publish
</button>
)}
<button className="m-3 btn btn-sm btn-danger" onClick={removeDevice}>
Delete
</button>
<button
type="submit"
className="btn btn-success"
onClick={updateContent}
>
Update
</button>
<p>{message}</p>
</div>
) : (
<div>
<br />
<p>Please click on a device.</p>
</div>
)}
</div>
);
};
export default Device;
And finally, this is my server.js code from back-end:
var express = require('express');
var bodyParser = require('body-parser');
const cors = require("cors");
var app = express();
var corsOptions = {
origin: "http://localhost:8083"
};
app.use(cors(corsOptions));
app.use(express.json());
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }));
const db = require('./app/config/db.config');
const Role = db.role;
db.sequelize.sync();
// db.sequelize.sync({ force: true }).then(() => {
// console.log("Drop and re-sync db.");
// initial();
// });
// CODE ABOVE MAY BE NECESSARY FOR DATABASE TESTING, ESPECIALLY IF DATABASE MIGRATION OCCURS BECAUSE THE "initial" FUNCTION ESTABLISHES ROLES, WHICH IS CRUCIAL
require("./app/router/router.js")(app);
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log("App listening at http://%s:%s", host, port)
})
function initial(){
Role.create({
id: 1,
name: "USER"
});
Role.create({
id: 2,
name: "ADMIN"
});
Role.create({
id: 3,
name: "PM"
});
}
Sending request is in a wrong format.
axios.post (url, data, {...headers here})

MongoDB - Error with Postman - Data sending fails

I have used Mean Stack to build a project. I have created a Report Form in which data can be inserted.
When I insert the data from the form the data is inserted to the collection.
But when I use Postman to insert data the data insertion fails.
Here are the code segments:
1.Front End Form - report.component.html
<form (ngSubmit)="savereportdata()" novalidate>
<ba-card>
<div class="form-group">
<label for="middleItemId">Item ID</label>
<input type="text" class="form-control" placeholder="Enter Item ID" [(ngModel)]="itemId" name="itemId">
</div>
<div class="form-group">
<label for="middleItemName">Item Name</label>
<input type="text" class="form-control" placeholder="Enter Item Name" [(ngModel)]="itemName" name="itemName">
</div>
<div class="form-group">
<label for="warrentyUntil">Warrenty Until</label>
<input type="date" readonly="" class="form-control">
</div>
<div class="form-group">
<label for="reportDescription">Description</label>
<textarea class="form-control" rows="3" [(ngModel)]="reportDescription" name="reportDescription"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</ba-card>
</form>
2.report.component.ts
import { NgModule,Component,Pipe,OnInit } from '#angular/core';
import { ReportItemService } from '../../../services/report-item.service'
#Component({
selector: 'app-report',
templateUrl: './report.component.html'
})
export class ReportComponent implements OnInit {
itemId:Number;
itemName:String;
reportDescription:String;
constructor(public reportservice:ReportItemService) {}
ngOnInit() {}
savereportdata() {
const reportitem = {
itemId:this.itemId,
itemName:this.itemName,
reportDescription:this.reportDescription
};
this.reportservice.reportitemdata(reportitem).subscribe(res=> {
console.log(res);
});
}
}
3.report-item.service.ts
import { Injectable } from '#angular/core';
import { Http,Headers} from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class ReportItemService {
reportitem:any;
constructor(private http:Http) {}
reportitemdata(reportitem) {
let headers=new Headers();
headers.append('Content-Type','application/json');
return this.http.post("http://localhost:3000/reportItem",reportitem,{headers:headers}).map(res=>res.json());
}
}
4.Backend Model - report.js
const mongoose = require('mongoose');
const schema = mongoose.Schema;
const reportSchema = new schema({
itemId: { type: Number, required: true },
itemName: { type: String },
reportDescription: { type: String },
date: { type: Date }
});
module.exports = mongoose.model("ReportItem", reportSchema);
module.exports.saveReportItem = function(newreport, callback) {
console.log(newreport);
newreport.save(callback);
};
5.router - reportItem.js
const express = require('express');
const router = express.Router();
const config = require('../config/database');
const ReportItem = require('../models/request-report/report');
router.post("", function(req, res) {
const newreport = new ReportItem({
itemId: req.body.itemId,
itemName: req.body.itemName,
reportDescription: req.body.reportDescription,
date: new Date
});
ReportItem.saveReportItem(newreport, function(err, report) {
if (err) {
res.json({ state: false, msg: "data not inserted" });
}
if (report) {
res.json({ state: true, msg: "data inserted" });
}
});
});
module.exports = router;
The Screenshot of the results when data is inserted from the form:
The Screenshot of the Error in Postman:
I've been trying to figure out this problem for weeks but couldn't.
Thanks loads in advance!
You could try using the bodyParser module in the js code to grab the data from the request. I’ve had issues with this in the past.

Multer is uploading my image locally but not in my database

I Want to upload a image on my blog post and there is an error, image is alredy in the folder but when i see the database there is noimage.png set as default ...
Im using Multer , there is my code :
Addpost.ejs
<% include ./partials/header %>
<form method="POST" action="/posts/add" enctype="multipart/form-data">
<div class="form-group">
<label>Title</label>
<input class="form-control" name="title" type="text">
</div>
<div class="form-group">
<label>Category</label>
<select class="form-control" name="category">
<% categories.forEach(function(category){ %>
<option value="<%= category.title %>"><%= category.title %></option>
<% }) %>
</select>
</div>
<div class="form-group">
<label>Body</label>
<textarea class="form-control" name="body"></textarea>
</div>
<div class="form-group">
<label>Main Image</label>
<input class="form-control" name="file" type="file">
</div>
<div class="form-group">
<label>Author</label>
<select class="form-control" name="author">
<option value="Arsen Cenko">Arsen Cenko</option>
<option value="John Doe">John Doe</option>
</select>
</div>
<input class="btn btn-default" name
="submit" type="submit" value="save">
</form>
<script src="/app.js"></script>
PostSchema :
var mongoose = require("mongoose")
var postSchema = new mongoose.Schema({
title: String,
created: {type: Date, default: Date.now},
category: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Category"
}
],
body: String,
file: String })
module.exports = mongoose.model("Post", postSchema);
Post.js Route
var express = require("express");
var router = express.Router();
var Post = require("../models/post");
var Category = require("../models/category");
var path = require('path');
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/images/uploads/')
},
filename: function (req, file, cb) {
cb(null, Date.now() + path.extname(file.originalname))
} });
var upload = multer({ storage: storage });
router.get("/add", function(req, res) {
Category.find({}, function(err, categories){
if(err){
console.log(err);
} else{
res.render("addpost", {
title: "Add Post",
categories: categories
})
}
})
})
router.post("/add", upload.single('image'), function(req, res){
var title = req.body.title;
var category = req.body.category;
var body = req.body.body;
var author = req.body.author;
if(req.files && req.files.image){
var imageOriginalName = req.files.image.originalname;
var imageName = req.files.image.fieldname;
var imageMime = req.files.image.mimetype;
var imagePath = req.files.image.path;
var imageExt = req.files.image.extension;
var imageSize = req.files.image.size;
} else {
var imageName = "noimage.png";
}
var newPost = {title:title, category:category, body:body, author:author, image:imageName};
Post.create(newPost, function(err, newPost){
if(err){
console.log("Error");
} else{
res.redirect("/");
}
})
})
Thanks :)
Hey according to documentation
https://github.com/expressjs/multer
using upload.single('image') will get your file in "req.file" not in "req.files"
I think this is the reason your if case fails and jumps to else case. You cannot access it like req.file.image.filename you can simply access it via req.file.filename. Since it is already a "single" file. try console logging the req.file to know what you are getting.
update I think mistake is in your html
<input class="form-control" name="file" type="file">
should be
<input class="form-control" name="image" type="file">
the name attribute of the html should be same as the string in upload.single.
So in your case
upload.single('image')
Now you will receive file in req.file.
Hope it helps.

Angular2 - How to upload file with form data submit [(ngModel)] and save reference in MongoDB

I have this task page and want to upload a file with the form submit to the NodeJs express server.
#Component({
selector: 'tasks',
template: `<div mdl class="mdl-grid demo-content">
<div class="demo-graphs mdl-shadow--2dp mdl-color--white mdl-cell mdl-cell--8-col">
<h3>Create Task Page</h3>
<form action="#" (ngSubmit)="onSubmit()">
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input class="mdl-textfield__input" type="text" id="taskname" [(ngModel)]="data.taskname"/>
<label class="mdl-textfield__label" for="taskname">Task Name</label>
</div> <br/>
<div class="mdl-textfield mdl-js-textfield">
<textarea class="mdl-textfield__input" type="text" rows= "5" id="taskdesc" [(ngModel)]="data.taskdesc"></textarea>
<label class="mdl-textfield__label" for="taskdesc">Task Description</label>
</div> <br/>
<select [(ngModel)]="data.assignedto">
<option *ngFor="#assign of dropdownValues" [ngValue]="assign.userEmail">{{assign.userEmail}}</option>
</select>
<div> <input type="file" placeholder="Upload file..."></div> <--How to handle this ?
<br/><br/> <button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored" type="submit">Create Task</button>
</form>
</div>
`,
directives: [ROUTER_DIRECTIVES, MDL]
})
export class CreateTaskComponent implements OnInit {
data: any;
onSubmit(form) {
console.log(JSON.stringify(this.data));
this.apartmentService.postTasks(this.data).then(_=>this.router.navigate(['Tasks']));
this.data = {};
}
}
The data is posted to the expressjs server as follows
Server.ts
router.route('/api/newtask')
.post(function(req, res) {
var task = new Task();
task.taskname = req.body.taskname;
task.taskdesc = req.body.taskdesc;
task.assignedto = req.body.assignedto;
task.taskstatus = 'OPEN';
task.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Task created!' });
});
})
The mongoose mondel for the mongodb is as follows.
Mongoose Model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TaskSchema = new Schema({
taskname: String,
taskdesc: String,
taskcreator:String,
createddate: String,
assignedto: String,
taskstatus: String
});
module.exports = mongoose.model('Task', TaskSchema);
How can I upload a file and associate it with the current data on the form ?
plz see this article https://www.npmjs.com/package/multer
you can use multer in server side and very easy :
var express = require('express')
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
var app = express()
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
})
app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
// req.files is array of `photos` files
// req.body will contain the text fields, if there were any
})
var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', cpUpload, function (req, res, next) {
// req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
//
// e.g.
// req.files['avatar'][0] -> File
// req.files['gallery'] -> Array
//
// req.body will contain the text fields, if there were any
})

Resources