gpt4 book ai didi

javascript - Mongoose 和 express : POST data from subdocument

转载 作者:行者123 更新时间:2023-11-30 19:32:45 26 4
gpt4 key购买 nike

我是 Express/Mongoose 和后端开发的新手。我正在尝试在我的架构中使用 Mongoose 子文档并将数据从表单发布到 MLab 数据库。

当我只使用父架构时,我成功地发布到数据库,但是当我尝试也从子文档发布数据时,我收到了一个未定义的错误。如何正确地从子文档发布数据?

这是我的架构:

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")
});

});

最佳答案

想通了。我没有使用点表示法正确访问这些值。

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 对象内的 .booksreq.body.books.bookTitle 应该是 req.body.bookTitle 等等。留下这篇文章以防它对其他人有帮助。

关于javascript - Mongoose 和 express : POST data from subdocument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56266606/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com