I am creating a small node/express/mongo app, which allows users to post cat photos and comment on them. I have two models, cat
, and comment
. Everything was working fine until I decided to associate the two models together, which then caused this error:
type: mongoose.Schema.Type.ObjectId,
^
TypeError: Cannot read property 'ObjectId' of undefined
The error is referring to the cat model:
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;
Here is the comment model :
var mongoose = require('mongoose');
var commentSchema = mongoose.Schema({
username: String,
content: String,
});
Comment = mongoose.model('Comment', commentSchema);
module.exports = Comment;
Here is a snippet of 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});
}
})
});
I am using mongoose 4.3.7 . I researched this problem and couldn't solve it. For example, I looked at this post and re-installed mongoose, but the problem persisted.
An ObjectID is a 12-byte Field Of BSON type. The first 4 bytes representing the Unix Timestamp of the document. The next 3 bytes are the machine Id on which the MongoDB server is running. The next 2 bytes are of process id. The last Field is 3 bytes used for increment the objectid.
It's a typo as there is no propery Type
to Schema
. It should be Types
instead:
comments: [{ "type": mongoose.Schema.Types.ObjectId, "ref": "Comment" }]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With