problem description
node.js+sequelize implements data addition, deletion, modification and query
the environmental background of the problems and what methods you have tried
the front page looks like this
"aa"
cannot get
:
related codes
/ / Please paste the code text below (do not replace the code with pictures)
server.js
var express = require("express"),
Sequelize=require("sequelize")
var bodyParser =require("body-parser")
var app = express();
var sequelize=new Sequelize(
"mind",
"root",
"123456",
{
"dialect": "mysql", // mysql
"host": "localhost", // ip
"port": 3306, //
"define": {
// _
"underscored": true
}
}
);
var Project=sequelize.define("Project",{
title:Sequelize.STRING,
description:Sequelize.TEXT,
created:Sequelize.DATE
});
var Task=sequelize.define("Task",{
title:Sequelize.STRING
});
Task.belongsTo(Project);
Project.hasMany(Task);
sequelize.sync();
app.set("view engine","jade");
app.set("views",__dirname+"/views");
app.set("view option",{layout:false});
app.use(express.static(__dirname+"/public"));
app.use(bodyParser.urlencoded({extended:true}));
//
app.get("/", function(req, res) {
Project.findAll().then(function(projects){
res.render("index",{projects:projects});
})
.catch(function (err){
console.log("error");
});
});
//
app.delete("/project/:id", function(req, res) {
Project.findById(Number(req.params.id)).then(function(projects){
projects.destroy()
.then(function(){
res.send(200);
})
.catch(function (err){
console.log("error");
});
}).catch(function (err){
console.log("error");
});
});
//
app.post("/projects", function(req, res) {
Project.build(req.body).save()
.then(function(obj){
res.send(obj);
})
.catch(function (err){
console.log("error");
});
});
//
app.get("/project/:id/tasks", function(req, res) {
Project.findById(Number(req.params.id))
.then(function(project){
project.getTasks().on("success",function(tasks){
res.render("tasks",{project:project,tasks:tasks});
})
})
.catch(function (err){
console.log("error");
});
});
//
app.post("/project/:id/tasks", function(req, res) {
res.body.ProjectId=req.params.id;
Task.build(req.body).save()
.then(function(obj){
res.send(obj);
})
.catch(function (err){
console.log("error");
});
});
//
app.delete("/task/:id", function(req, res) {
Task.findById(Number(req.params.id)).success(function(task){
task.destroy()
.then(function(){
res.send(200);
})
.catch(function (err){
console.log("error");
});
}).catch(function (err){
console.log("error");
});
});
app.listen(3000,function(){
console.log("listening to port 3000");
});