我正在创建一个小型 node/express/mongo 应用程序,它允许用户发布猫照片并对其进行评论。我有两个模型,cat
和 comment
。一切正常,直到我决定将这两个模型关联在一起,然后导致了这个错误:
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/