【发布时间】:2019-10-09 12:28:18
【问题描述】:
我是 Express/Mongoose 和后端开发的新手。我正在尝试在我的 Schema 中使用 Mongoose 子文档,并将表单中的数据 POST 到 MLab 数据库。
仅使用父架构时,我成功地 POST 到数据库,但是当我尝试也从子文档中 POST 数据时,我收到未定义的错误。如何正确 POST 子文档中的数据?
这是我的架构:
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;
这是我尝试 POST 到数据库的路线:
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")
});
});
【问题讨论】:
-
我面临同样的问题。你解决了吗?
-
我最终回答了我自己的问题。看看下面的下一个帖子。我没有使用点符号正确访问这些值。例如,
req.body.books.bookTitle应该是req.body.bookTitle。也许你也面临着类似的问题。
标签: javascript express mongoose schema subdocument