node.js - Mongoose /Node 错误 : Cannot read property 'ObjectId' of undefined

标签 node.js mongodb

我正在创建一个小型 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 。我研究了这个问题,但无法解决。例如,我查看了 this发布并重新安装 Mongoose ,但问题仍然存在。

最佳答案

这是一个拼写错误,因为 Schema 没有属性 Type。它应该是 Types:

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

关于node.js - Mongoose /Node 错误 : Cannot read property 'ObjectId' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35074133/

相关文章:

Node.js+Express 随机丢弃请求,导致网关超时

javascript - Electron 按钮配置

node.js - 将用户凭据从前端传递到 Node 后端的最安全方法是什么

mysql - 用于存储十亿封电子邮件的数据库模式

mongodb - 无法使用 'meteor mongo' 连接到本地(正在运行的)mongo

node.js - 在 Node.js 上通过 XMPP 连接到 Google Talk

javascript - 如何使用 fs.unlink 删除本地文件?

node.js - "systemctl start pm2-user-name"给出错误

node.js - 使用 mongoose hook 重试保存重复键错误

arrays - MongoDB:为什么 find 和 findOne 只返回最后一个数组元素?