Mongoose/node error:无法读取未定义的属性'ObjectId'

Fro*_*619 2 mongodb node.js

我正在创建一个小节点/ express/mongo应用程序,它允许用户发布猫照片并对其进行评论.我有两个型号cat,和comment.一切都工作正常,直到我决定将两个模型关联起来,然后导致了这个错误:

type: mongoose.Schema.Type.ObjectId,
                            ^ 
TypeError: Cannot read property 'ObjectId' of undefined
Run Code Online (Sandbox Code Playgroud)

错误是指cat模型:

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;
Run Code Online (Sandbox Code Playgroud)

这是评论模型:

var mongoose = require('mongoose');

var commentSchema = mongoose.Schema({

    username: String,
    content: String,
});


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

module.exports = Comment;
Run Code Online (Sandbox Code Playgroud)

这是一个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});  
        }  
    })
});
Run Code Online (Sandbox Code Playgroud)

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

Bla*_*ven 10

这是一个错字,因为没有合适TypeSchema.它应该是Types:

comments: [{ "type": mongoose.Schema.Types.ObjectId, "ref": "Comment" }]
Run Code Online (Sandbox Code Playgroud)

  • 我在使用小写字母类型的mongoose.Schema.types.ObjectId时遇到了同样的问题。 (2认同)

Spr*_*tte 4

问题在于您的架构中的注释类型,但它看起来很好,但只需尝试:

  comments:[{ type: String, ref: 'Comment' }],
Run Code Online (Sandbox Code Playgroud)

或者

  comments: [{type: Schema.ObjectId, ref: "Comment"} 
Run Code Online (Sandbox Code Playgroud)