Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose/node error: Cannot read property 'ObjectId' of undefined

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.

like image 758
Frosty619 Avatar asked Jan 28 '16 23:01

Frosty619


People also ask

What is ObjectID in mongoose?

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.


1 Answers

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" }]
like image 69
Blakes Seven Avatar answered Sep 28 '22 09:09

Blakes Seven