使用mongoose将embedded文档的多个实例保存到我的模型中

我试图在我的模型中保存embedded式文档的多个实例,我期待每当我填写我的表单数据时,embedded式文档的一个新实例被创build并推送到一个数组中。

这是我的预测模式。

const mongoose = require('mongoose'); mongoose.Promise = global.Promise; const slug = require('slugs'); const teamSchema = new mongoose.Schema({ team1: { type: String }, team2: { type: String }, prediction:{ type: String } }); const predictionSchema = new mongoose.Schema({ author:{ type: String }, team: [ teamSchema ] }); module.exports = mongoose.model('Prediction', predictionSchema); 

这是我的控制器

 const mongoose = require('mongoose'); const Prediction = mongoose.model('Prediction'); exports.homePage = (req, res) => { res.render('layout', {title: 'Home'}); }; exports.addPrediction = (req, res) => { res.render('editPrediction', {title: 'Add Prediction'}); }; exports.createPrediction = async(req, res) => { const prediction = new Prediction({ author: req.body.author, team: { team1: req.body.team1, team2: req.body.team2, prediction: req.body.prediction } }); await prediction.save(); res.redirect('/'); }; 

和我的Form.pug

 form.ui.form.segment#register-form(action='/add' method='POST') .field label Name | .ui.left.labeled.icon.input input(type='text', placeholder='Name', name='author') | i.user.icon #fields - for(var i = 0; i < 2; i++) .field label Team 1 | .ui.left.labeled.icon.input input(type='text', placeholder='Team 1', name='team1') | i.soccer.icon .field label Team 2 | .ui.left.labeled.icon.input input(type='text', placeholder='Team 2', name='team2') | i.soccer.icon .field label Prediction | .ui.left.labeled.icon.input input(type='text', placeholder='Prediction', name='prediction') | i.lock.icon button.ui.button.fluid(type='submit') Save 

当我尝试保存预测的一个实例时,保存在模型中的数据如屏幕截图所示。

数据库一个实例

当我尝试从表单中保存两个预测的实例时。 团队的第二个实例只是追加到第一个实例中,而不是作为一个新的对象被推入团队Array中。

数据库多个实例

我需要创build一个新文档,并在我想从表单保存团队的多个实例时将其推送到团队数组中。 我错过了什么?

您的模式是正确的。我的build议是使用var关键字而不是const因为variables是一个数据结构,其中包含预期会更改的信息。 常量是包含永远不会改变的信息的数据结构。 如果有错误的余地,应该始终使用var。 但是,并不是所有在程序生命周期中都不会改变的信息都需要用const声明。 如果在不同的情况下信息应该改变,使用var来表示,即使实际的改变没有出现在你的代码中。试试看看是否有效。