【问题标题】:Mongoose & Express: POST data from subdocumentMongoose & Express:从子文档发布数据
【发布时间】: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


【解决方案1】:

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

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
    }

无需访问书籍对象内部的.booksreq.body.books.bookTitle 应该是 req.body.bookTitle 等等。留下这篇文章以防它帮助别人。

【讨论】:

    猜你喜欢
    • 2021-05-16
    • 2017-09-25
    • 2016-06-14
    • 2014-02-10
    • 2015-06-02
    • 2012-11-04
    • 1970-01-01
    • 2015-03-27
    • 2018-04-01
    相关资源
    最近更新 更多