【问题标题】:Save multiple instances of an embedded document to my model using mongoose使用 mongoose 将嵌入文档的多个实例保存到我的模型中
【发布时间】:2017-08-12 14:58:41
【问题描述】:

我正在尝试在我的模型中保存多个嵌入文档的实例,并且我希望每次填写表单数据时,都会创建一个嵌入文档的新实例并将其推送到数组中。

这是我的预测架构。

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

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

当我尝试从表单中保存两个预测实例时。团队的第二个实例只是附加到第一个实例中,而不是创建为推送到团队数组中的新对象。

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

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

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

    【讨论】:

    • 嘿。感谢您的建议,但我尝试更改为 var 但仍然得到相同的结果
    猜你喜欢
    • 2011-11-27
    • 1970-01-01
    • 2017-08-30
    • 1970-01-01
    • 2014-04-15
    • 2018-10-25
    • 1970-01-01
    • 2018-09-20
    • 2013-12-27
    相关资源
    最近更新 更多