Я создаю один полный стек, используя MERN (MongoDB, Express, React js и Node). В настоящее время я работаю над своим бэкэндом. Я использую REST API и для тестирования HTTP-запроса я использую Почтальон. Моя цель, где студент может взять несколько уроков. Например: гимнастика 1, фитнес и т. Д.
Я создал две таблицы. Один - это стол для студентов, а другой - стол для курса. Я сделал отношения между двумя таблицами. Но проблема в том, что, когда я добавляю новые данные с тем же именем человека и подробностями, он показывает другой набор данных. Я не знаю, как предотвратить повторяющиеся данные имени.
Моя цель такова:
{
"students": [
{
"id": 1,
"name": "Anni Anonen",
"birthday": "1992-02-28",
"address": "Kivakatu 1",
"zipcode": "00500",
"city": "Helsinki",
"phone": "+358506760702",
"email": "anni.anonen@testing.fi",
"courses": [1]
},
{
"id": 2,
"name": "Ville Anonen",
"birthday": "2000-03-28",
"address": "Hämeentie 1",
"zipcode": "00510",
"city": "Helsinki",
"phone": "+358508660702",
"email": "ville.anonen@testing.fi",
"courses": [1]
},
{
"id": 3,
"name": "Tapani Kumpu",
"birthday": "1999-05-28",
"address": "Jokukatu 17",
"zipcode": "00560",
"city": "Helsinki",
"phone": "+358502330702",
"email": "tapani.kumpu@testing.fi",
"courses": [1]
},
{
"id": 4,
"name": "Milla Moilanen",
"birthday": "1989-07-21",
"address": "Testikatu 3",
"zipcode": "00720",
"city": "Helsinki",
"phone": "+358501750702",
"email": "milla.moilanen@testing.fi",
"courses": [2]
},
{
"id": 5,
"name": "Maria Manninen",
"birthday": "2002-09-28",
"address": "Vilhonkatu 12",
"zipcode": "00800",
"city": "Helsinki",
"phone": "+358509890702",
"email": "maria.manninen@testing.fi",
"courses": [2, 3]
},
{
"id": 6,
"name": "Konsta Koistinen",
"birthday": "2003-010-20",
"address": "Pasilan raitti 21",
"zipcode": "00100",
"city": "Helsinki",
"phone": "+358504760702",
"email": "konsta.koistinen@testing.fi",
"courses": [1, 3]
}
],
"courses": [
{
"id": 1,
"name": "Gymnastics 1",
"startdate": "2020-01-01",
"enddate": "2020-02-10"
},
{
"id": 2,
"name": "Gymnastics 2",
"startdate": "2020-01-01",
"enddate": "2020-02-10"
},
{
"id": 3,
"name": "Fitness 1",
"startdate": "2020-02-01",
"enddate": "2020-02-20"
},
{
"id": 4,
"name": "Dance 1",
"startdate": "2020-05-01",
"enddate": "2020-05-02"
}
]
}
Это мой express сервер с Rest API
require("dotenv").config();
const express = require("express");
const app = express();
const morgan = require("morgan");
const helmet = require("helmet");
const cors = require("cors");
const mongoose = require("mongoose");
const student = require("./models/student");
const course = require("./models/course");
//app middlewear
app.use(morgan("common"));
app.use(helmet());
app.use(cors());
app.use(express.json()); //body Parser
//Connect to db
mongoose
.connect(process.env.MONGODB_URI, {
useUnifiedTopology: true,
useNewUrlParser: true
})
.then(() => console.log("DB Connected!"))
.catch(err => {
console.log(err);
});
//student
app.get("/students", async (req, res, next) => {
try {
await student
.find()
.populate("course")
.select("name birthday address zipcode city phone email")
.then(docs => {
const response = {
count: docs.length,
students: docs
};
res.json(response);
});
} catch (error) {
console.log(error);
}
});
app.get("/students/:id", async (req, res, next) => {
const id = req.params.id;
try {
student
.findById(id)
.exec()
.then(data => {
console.log(data);
res.json(data);
});
} catch (error) {
console.log(error);
}
});
app.put("/students/:id", async (req, res, next) => {
const id = req.params.id;
const update = {};
for (const datas of req.body) {
update[datas.updateData] = datas.value;
}
try {
student
.update({ _id: id }, { $set: update })
.exec()
.then(data => {
res.json(data);
});
} catch (error) {
console.log(error);
}
});
app.delete("/students/:id", async (req, res, next) => {
const id = req.params.id;
try {
student
.remove({ _id: id })
.exec()
.then(data => {
res.json(data);
});
} catch (error) {
console.log(error);
}
});
app.post("/students", async (req, res, next) => {
const logs = new student({
_id: mongoose.Types.ObjectId(),
name: req.body.name,
birthday: req.body.birthday,
address: req.body.address,
zipcode: req.body.zipcode,
city: req.body.city,
phone: req.body.phone,
email: req.body.email,
course: req.body.courseid
});
logs
.save()
.then(data => {
console.log(data);
res.json(data);
})
.catch(err => {
console.log(err);
});
});
//course
app.get("/courses", async (req, res, next) => {
try {
await course
.find()
.select("name student startdate enddate")
.then(docs => {
const response = {
count: docs.length,
courses: docs
};
res.json(response);
});
} catch (error) {
console.log(error);
}
});
app.get("/courses/:id", async (req, res, next) => {
const id = req.params.id;
try {
course
.findById(id)
.select("name student startdate enddate")
.exec()
.then(data => {
console.log(data);
res.json(data);
});
} catch (error) {
console.log(error);
}
});
app.put("/courses/:id", async (req, res, next) => {
const id = req.params.id;
const update = {};
for (const datas of req.body) {
update[datas.updateData] = datas.value;
}
try {
course
.update({ _id: id }, { $set: update })
.exec()
.then(data => {
res.json(data);
});
} catch (error) {
console.log(error);
}
});
app.delete("/courses/:id", async (req, res, next) => {
const id = req.params.id;
try {
course
.remove({ _id: id })
.exec()
.then(data => {
res.json(data);
});
} catch (error) {
console.log(error);
}
});
app.post("/courses", async (req, res, next) => {
const logs = new course({
_id: mongoose.Types.ObjectId(),
name: req.body.name,
startdate: req.body.startdate,
enddate: req.body.enddate
});
logs
.save()
.then(data => {
console.log(data);
res.json(data);
})
.catch(err => {
console.log(err);
});
});
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`? App is listening at port ${port}!`));
Это моя схема ученика
const mongoose = require("mongoose");
const { Schema } = mongoose;
const studentModel = new Schema({
_id: mongoose.Schema.Types.ObjectId,
name: {
type: String,
required: true
},
birthday: {
type: Date,
required: true
},
address: {
type: String,
required: true
},
zipcode: {
type: Number,
required: true
},
city: {
type: String,
required: true
},
phone: {
type: Number,
required: true
},
email: {
type: String,
required: true
},
course: {
type: mongoose.Schema.Types.ObjectId,
ref: "Course",
required: true
}
});
const student = mongoose.model("Student", studentModel);
module.exports = student;
Это схема курса
const mongoose = require("mongoose");
const { Schema } = mongoose;
const courseModel = new Schema({
name: {
type: String,
required: true
},
startdate: {
type: Date,
required: true
},
enddate: {
type: Date,
required: true
}
});
const course = mongoose.model("Course", courseModel);
module.exports = course;
дубликат визуализация результата