首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mongoose & Express:从子文档发布数据

Mongoose & Express:从子文档发布数据
EN

Stack Overflow用户
提问于 2019-05-23 08:27:52
回答 1查看 683关注 0票数 1

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

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

这是我的架构:

代码语言:javascript
复制
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;

下面是我尝试发送到数据库的路径:

代码语言:javascript
复制
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")
    });

});
EN

回答 1

Stack Overflow用户

发布于 2019-05-23 08:56:49

我想通了。我没有使用点符号正确地访问这些值。

代码语言:javascript
复制
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,依此类推。留下这篇文章,以防它对其他人有帮助。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56266606

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档