2017-06-11 21 views
1

サーバーからエラーが発生しました。500エラー:ObjectIdへのキャストが値のために失敗しました

:私は次のルートを持っている

getAuthors() { 
     return this.http.get(this.appConfig.urlServer + "/comment/authors") 
      .map((response: Response) => response.json()); 
} 

var mongoose = require("mongoose"); 
var Schema = mongoose.Schema; 

var commentSchema = new Schema({ 
    author: String, 
    title: String, 
    text: String, 
    favorite: Number 
}); 

var Comment = mongoose.model("Comment", commentSchema); 

module.exports = Comment; 

私はメソッドを使用して要求を送信する角度2で記述されたクライアントから:

"{"message":{"message":"Cast to ObjectId failed for value \"authors\" at path \"_id\" for model \"Comment\"","name":"CastError","stringValue":"\"authors\"","kind":"ObjectId","value":"authors","path":"_id"}}"

私はモデルを持っています

var express = require("express"); 
var mongoose = require("mongoose"); 
var Comment = require("../models/comment"); 
var router = express.Router(); 

router.get("/comment/authors", getAuthorsOfComments); 

module.exports = router; 

function getAuthorsOfComments(req, res) { 
    Comment.find({}, 'author', function(err, authors) { 
    if (err) { 
     res.status(500).json({ 
     message: err 
     }) 
    } 

    if (authors) { 
     res.status(200).json({ 
     authors: authors 
     }) 
    } 
    }) 
} 

お願いします。なぜ私はエラーが発生するのか分かりません。コメントのコレクションから

UPDATE 1.

エントリー。 最初のエントリ:

{ 
    "_id" : ObjectId("59269000483977cefe7961e0"), 
    "author" : "test", 
    "title" : "title of text", 
    "text" : "Big text", 
    "favorite" : 1 
} 

2番目のエントリ:

{ 
    "_id" : ObjectId("5926901b483977cefe7961f2"), 
    "author" : "test2", 
    "title" : "title of text", 
    "text" : "Big text", 
    "favorite" : 5 
} 
+0

コメントコレクションからいくつかのエントリを投稿できますか? – Shadowfool

+0

はい、できます。私は自分の投稿を更新しました。 –

+0

投稿したコードを正確に使用していますか?あなたのコードはうまく見え、エラーなく動作するはずです。 –

答えて

0

実際の問題は、あなたが適切にデータベースを照会していないと、適切にコールバック関数を呼び出していない、あなたのクエリの方法です。私はあなたの質問コードを書き換えます。

function getAuthorsOfComments(req, res) { 
    Comment.find({}, {author: 1}).then(function(err, authors) { 
    if (err) { 
     res.status(500).json({ 
     message: err 
     }) 
    } 

    if (authors) { 
     res.status(200).json({ 
     authors: authors 
     }) 
    } 
    }) 
} 

{著者:1}だけ著者を返すためのMongoDBに伝えます。 1の代わりに0を指定すると、mongoDBはすべてのフィールドを返しますが、作成者は返しません。

+0

OPのクエリに問題はありません。彼の質問は完璧です。 –

+0

このリンクを参照してください:http://mongoosejs.com/docs/queries.html –

+0

私はエラーの理由を説明します。私はルートの他のメソッドで不正なURLを書いたので、データベースへのクエリを実行しませんでした。 –

関連する問題