2017-06-11 45 views
1

我从服务器收到错误消息。500错误:强制转换为ObjectId失败值

"{"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 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写入我使用的方法来发送请求的客户端:

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

我有下一个路由:

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 
} 

第二个条目:

{ 
    "_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的只返回作者。如果你把0而不是1,mongoDB将返回所有字段,但不是作者。

+0

我没有看到OP的查询有任何问题。他的查询非常好。 –

+0

看到这个链接:http://mongoosejs.com/docs/queries.html –

+0

我发现了错误的原因。我在路由的其他方法中写了不正确的URL,所以我没有执行查询到数据库。 –

相关问题