2016-11-30 26 views
0

を保存する前に、私はモデルを持っている:マングース更新モデル

const wordSchema = mongoose.Schema({ 
    author: {type: Object, default: 'unknown'}, 
    quote: String, 
    source: {type: String, default: 'unknown', index: true}, 
    rating: {type: Number, default: 0}, 
    createdAt: {type: Date, default: Date.now}, 
    updatedAt: {type: Date, default: Date.now}, 
}); 

は今、私のサーバーにPOSTリクエストを受け取った後、私はウィキペディアにGETリクエストを作成し、作成者情報を取得、その後にそれを追加したい 私のモデルをオブジェクトとして作成し、このモデルをデータベースに書き込みます。

app.post('/', function(req, res) { 
    let author = {}; 
    let quote = new Word({ 
    author: req.body.author, 
    quote: req.body.quote, 
    source: req.body.source, 
    rating: req.body.rating, 
    }); 
    let authorName = req.body.author.replace(/ /g, '%20'); 
    let url = 'https://en.wikipedia.org/w/api.php?action=query&format=json&titles=' + authorName + '&prop=pageimages|extracts&pithumbsize=200&exsentences=10&exintro=true'; 
    request.get(url, (error, response, body) => { 
    if(error) { 
     return error; 
    } 
    let data = JSON.parse(body); 
    let pageID; 
    for(page in data.query.pages) { 
     pageID = page; 
    } 
    author = { 
     name: req.body.author, 
     thumbnail: data.query.pages[pageID].thumbnail.source, 
     flavorText: data.query.pages[pageID].extract, 
    }; 
    }); 
    // Save the quote 
    quote.pre('save', (next) => { 
    this.author = author; 
    }) 
    quote.save(function(err, quote) { 
    if (err) { 
     res.send(err); 
    } 
    res.redirect('/words'); 
    }); 
}); 

は今、私は.pre機能で値を更新しようとしたが、私は

quote.preがやっての「正しい方法だろうどのような機能

ではありません取得していますこれと私は間違って何をしていますか?

答えて

0

quoteはマングーススキーマではありませんが、wordSchemaので、それは以下のようにする必要がある:

wordSchema.pre('save', (next) => { 
    this.quote = whteverYouWantToAssignWith; 
}) 

しかし、実際にあなたが私の知る限り理解してご利用の場合にはそれを必要としない、あなたが達成することができますあなたは次のように欲しいもの:これで

app.post('/', function(req, res) { 
    let authorName = req.body.author.replace(/ /g, '%20'); 
    let url = 'https://en.wikipedia.org/w/api.php?action=query&format=json&titles=' + authorName + '&prop=pageimages|extracts&pithumbsize=200&exsentences=10&exintro=true'; 
    request.get(url, (error, response, body) => { 
    if(error) { 
     return error; 
    } 
    let data = JSON.parse(body); 
    let pageID; 
    for(page in data.query.pages) { 
     pageID = page; 
    } 

    let quote = new Word({ 
     author: { 
     name: req.body.author, 
     thumbnail: data.query.pages[pageID].thumbnail.source, 
     flavorText: data.query.pages[pageID].extract, 
     }, 
     quote: req.body.quote, 
     source: req.body.source, 
     rating: req.body.rating, 
    }); 

    quote.save(function(err, quote) { 
     if (err) { 
     res.send(err); 
     } 
     res.redirect('/words'); 
    }); 
    }); 
}); 
+0

、私はちょうどwordSchemaを取得していますと、あなたは、スキーマはもちろんのない要求機能の中で定義されたコードのこの部分を配置する必要があり –

+0

定義されていません。 –

+0

したがって、httpリクエストの機能全体をスキーマファイルに移動することをお勧めしますか? –