我是Express/Mongoose和后端开发的新手。我正尝试在我的模式中使用Mongoos子文档,并将表单中的数据发布到MLab数据库。
当我只使用父模式时,我成功地POSTing到了数据库,但是当我尝试从子文档中发送数据时,我得到了一个未定义的错误。如何从子文档中正确发布数据?
这是我的架构:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bookSchema = new Schema({
bookTitle: {
type: String,
required: true
},
author: {
type: String,
required: true
},
genre: {
type: String
}
});
const userSchema = new Schema({
name: String,
username: String,
githubID: String,
profileUrl: String,
avatar: String,
// I've tried this with bookSchema inside array brackets and also
//without brackets, neither works
books: [bookSchema]
});
const User = mongoose.model('user', userSchema);
module.exports = User;下面是我尝试发送到数据库的路径:
router.post('/', urlencodedParser, (req, res) => {
console.log(req.body);
const newUser = new User({
name: req.body.name,
username: req.body.username,
githubID: req.body.githubID,
profileUrl: req.body.profileUrl,
avatar: req.body.avatar,
books: {
// All of these nested objects in the subdocument are undefined.
//How do I properly access the subdocument objects?
bookTitle: req.body.books.bookTitle,
author: req.body.books.author,
genre: req.body.books.genre
}
});
newUser.save()
.then(data => {
res.json(data)
})
.catch(err => {
res.send("Error posting to DB")
});
});发布于 2019-05-23 08:56:49
我想通了。我没有使用点符号正确地访问这些值。
books: {
// All of these nested objects in the subdocument are undefined.
//How do I properly access the subdocument objects?
bookTitle: req.body.books.bookTitle,
author: req.body.books.author,
genre: req.body.books.genre
}不需要访问books对象内部的.books。req.body.books.bookTitle应该是req.body.bookTitle,依此类推。留下这篇文章,以防它对其他人有帮助。
https://stackoverflow.com/questions/56266606
复制相似问题