[英]When making a POST request for a subdocument it comes back as undefined? mongoose, express
我正在嘗試發出將新數據保存到我的子文檔之一的發布請求,但在嘗試訪問 function 中的子文檔時出現錯誤。它一直返回為未定義。 如何通過 id 獲取特定用戶並創建和添加新數據到它的子文檔?
model
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const ClassworkSchema = new Schema({
name: String,
time: Date,
todo: String,
isDone: false
});
const OutcomesSchema = new Schema({
name: String,
time: Date,
todo: String,
isDone: false,
isApproved: false
})
const MeetupSchema = new Schema({
name: String,
time: Date,
location: String,
attended: false
})
const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
},
classwork:{type: [ClassworkSchema], default: []},
outcomes: [OutcomesSchema],
meetups: [MeetupSchema],
});
module.exports = User = mongoose.model('users', UserSchema);
controller
classworkRouter.post("/:userId/", (req, res) => {
User.findById(req.params.user_id, (err, user) => {
if (err) return err;
new_classwork = new classwork();
(new_classwork.name = req.body.name),
(new_classwork.date = req.body.date),
(new_classwork.todo = req.body.todo),
(new_classwork.isDone = req.body.isDone);
console.log(new_classwork);
user.classwork = {};
user.classwork.name = req.body.classwork.name;
user.classwork.todo = user.classwork.todo;
if (user.classwork === undefined) {
user.classwork.push(new_classwork);
} else {
user.classwork = [new_classwork];
}
user.save(function (err, data) {
if (err) res.send(err);
res.json({ message: "work added", data: data });
});
});
});
您可以在以下照片中看到終端中的錯誤:
在這部分代碼中
new_classwork = new classwork()
你應該這樣定義 new_classwrok :
let new_classwork = new classwork()
並且未定義new classwork()
,您必須在 controller 中要求 Model 的 classwork..
在這樣的模式文件導出模式中:
const User = mongoose.model('users', UserSchema);
const Classwork = mongoose.model('Classwork', ClassworkSchema );
module.exports = {
User : User ,
Classwork : Classwork
}
在 controller.js
const {User} = require('../models/certification');
const {Classwork } = require('../models/certification');
在需要模型之后,您可以像這樣使用new Crosswork
:
注意:帶有大寫字符的課業
let new_classwork = new Classwork()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.