2017-08-11 2 views
1

モデルに埋め込みドキュメントの複数のインスタンスを保存しようとしていますが、フォームデータを埋め込むたびに埋め込みドキュメントの新しいインスタンスが作成され、配列にプッシュされます。mongooseを使用して埋め込みドキュメントの複数のインスタンスを保存する

これは私の予測スキーマです。

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); 

これは私が予測の1つのインスタンスを保存しようとすると、モデル内に保存されたデータは次のように示されている私のコントローラ

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 

ですスクリーンショット。

Database One Instance

私は、フォームからの予測の2つのインスタンスを保存しようとします。チームの2番目のインスタンスは最初のインスタンスに追加され、チームのArrayにプッシュされる新しいオブジェクトとして作成されません。

Database Multiple Instances

は、私は、新しい文書が作成され、私は自分のフォームからチームの複数のインスタンスを保存する際に、チームの配列にプッシュする必要があります。 私は何を欠席しましたか?

答えて

0

あなたのスキーマは正しいです。変数は変更される予定の情報を含むデータ構造体なので、constの代わりにvarキーワードを使用しています。定数とは決して変化しない情報を含むデータ構造です。エラーの余地がある場合は、常にvarを使用する必要があります。しかし、プログラムの存続期間中に決して変化しないすべての情報をconstで宣言する必要はありません。異なる状況下で情報を変更する必要がある場合は、実際の変更がコード内に現れていない場合でも、varを使用してその情報を示します。これを試して、これが機能するかどうかを確認してください。

+0

ねえ。提案をありがとうが、私はvarに変更しようとしたが、同じ結果を得ている – Kimkykie

関連する問題