Node.js Mongoose/节点错误:无法读取属性';ObjectId';未定义的
我正在创建一个小node/express/mongo应用程序,允许用户发布cat照片并对其进行评论。我有两种型号,Node.js Mongoose/节点错误:无法读取属性';ObjectId';未定义的,node.js,mongodb,Node.js,Mongodb,我正在创建一个小node/express/mongo应用程序,允许用户发布cat照片并对其进行评论。我有两种型号,cat和comment。一切正常,直到我决定将两个模型关联在一起,这导致了以下错误: type: mongoose.Schema.Type.ObjectId, ^ TypeError: Cannot read property 'ObjectId' of undefined 该错误与cat型号有关: var mongoose
cat
和comment
。一切正常,直到我决定将两个模型关联在一起,这导致了以下错误:
type: mongoose.Schema.Type.ObjectId,
^
TypeError: Cannot read property 'ObjectId' of undefined
该错误与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;
以下是注释模型:
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});
}
})
});
我使用的是猫鼬4.3.7。我研究了这个问题,但解决不了。例如,我查看了post并重新安装了mongoose,但问题仍然存在。问题在于您的模式中的注释类型,但它看起来很好,但请尝试:
comments:[{ type: String, ref: 'Comment' }],
或
这是一个输入错误,因为没有属性
Type
到Schema
。它应该是类型
:
comments: [{ "type": mongoose.Schema.Types.ObjectId, "ref": "Comment" }]
我在
mongoose.Schema.types.ObjectId中遇到了同样的问题,使用了小写类型。祝福这个答案
comments: [{ "type": mongoose.Schema.Types.ObjectId, "ref": "Comment" }]