[英]When making a POST request for a subdocument it comes back as undefined? mongoose, express
I'm trying a to make a post request to save new data to one of my subdocuments, but I'm getting an error when trying to access the subdocument in the function. It keeps coming back as undefined.我正在尝试发出将新数据保存到我的子文档之一的发布请求,但在尝试访问 function 中的子文档时出现错误。它一直返回为未定义。 How can I get a specific user by id and create and add new data the one it's subdocuments?
如何通过 id 获取特定用户并创建和添加新数据到它的子文档?
model 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 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 });
});
});
});
you can see the error in the terminal in the following phto:您可以在以下照片中看到终端中的错误:
in this part of code在这部分代码中
new_classwork = new classwork()
you shoud defined the new_classwrok like this:你应该这样定义 new_classwrok :
let new_classwork = new classwork()
and new classwork()
is not defined, you must to require Model of classwork in controller..并且未定义
new classwork()
,您必须在 controller 中要求 Model 的 classwork..
in schema file export schemas like this:在这样的模式文件导出模式中:
const User = mongoose.model('users', UserSchema);
const Classwork = mongoose.model('Classwork', ClassworkSchema );
module.exports = {
User : User ,
Classwork : Classwork
}
in controller.js在 controller.js
const {User} = require('../models/certification');
const {Classwork } = require('../models/certification');
after require models you can use new Crosswork
like this:在需要模型之后,您可以像这样使用
new Crosswork
:
note : Classwork with uppercase character注意:带有大写字符的课业
let new_classwork = new Classwork()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.