Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/463.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 猫鼬;Express:从子文档发布数据_Javascript_Express_Mongoose_Schema_Subdocument - Fatal编程技术网

Javascript 猫鼬;Express:从子文档发布数据

Javascript 猫鼬;Express:从子文档发布数据,javascript,express,mongoose,schema,subdocument,Javascript,Express,Mongoose,Schema,Subdocument,我是Express/Mongoose和后端开发的新手。我试图在模式中使用Mongoose子文档,并将数据从表单发布到MLab数据库 仅使用父模式时,我成功地将数据发布到数据库中,但当我尝试同时发布子文档中的数据时,我得到了一个未定义的错误。如何正确发布子文档中的数据 这是我的模式: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const bookSchema = new Schema({ boo

我是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;
以下是我尝试发布到数据库的路径:

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

我也面临同样的问题。你解决了吗?我最后回答了我自己的问题。看下面的下一个帖子。我没有正确地使用点符号访问值<例如,code>req.body.books.bookTitle应该是
req.body.bookTitle
。也许你也面临着类似的问题。