Mongoose/Node错误:无法读取未定义的'ObjectId'属性

7
我正在创建一个小型的node/express/mongo应用程序,允许用户发布猫咪照片并对其进行评论。我有两个模型:catcomment。一切都运行良好,直到我决定将这两个模型关联起来,这导致了以下错误:
type: mongoose.Schema.Type.ObjectId,
                            ^ 
TypeError: Cannot read property 'ObjectId' of undefined

错误是指的“猫”模型:
var mongoose = require('mongoose');


var catModel = mongoose.Schema({
    name: String,
    image: String,
    owner: String,  
    description: String,
    comments: [

        {
            type: mongoose.Schema.Type.ObjectId,
            ref: "Comment"

        } 
    ]
});

var Cat = mongoose.model("Cats", catModel);

module.exports = Cat;

这是评论模型:

var mongoose = require('mongoose');

var commentSchema = mongoose.Schema({

    username: String,
    content: String,
});


Comment = mongoose.model('Comment', commentSchema);

module.exports = Comment;

这里是 app.js 的片段:

var express = require('express');
var app = express();
//more modules
var Comment = require('./models/comment.js');
var Cat = require('./models/cat.js');


//home route 

app.get('/cats', function(req,res) {

    Cat.find({}, function(err, cats) {
        if (err) {
            console.log(err);

        } else {
          res.render('cats', {cats: cats});  
        }  
    })
});

我正在使用mongoose 4.3.7。我研究了这个问题,但无法解决。例如,我查看了这篇文章并重新安装了mongoose,但问题仍然存在。

2个回答

18

由于Schema中没有适当的属性Type,这是一个拼写错误。应该使用Types代替:

comments: [{ "type": mongoose.Schema.Types.ObjectId, "ref": "Comment" }]

3
我遇到了与 mongoose.Schema.types.ObjectId 相同的问题,使用小写的 types。 - Kurt Van den Branden
感谢这个答案。我差点就要在桌子上撞头了。 - amanthethy
这是件事。 - CodeWorld

4
问题出在你的模式中,标记的类型是评论,看起来很好,但是请尝试一下:
  comments:[{ type: String, ref: 'Comment' }],

或者
  comments: [{type: Schema.ObjectId, ref: "Comment"} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接