2

I am trying to create a hierarchy of categories in MongoDB for use with Node.js via Mongoose. I am using the Array of Ancestors approach (http://docs.mongodb.org/manual/tutorial/model-tree-structures-with-ancestors-array/) and have already saved the hierarchy in the database. Directly from Mongo an element looks like this:

{ 
    "_id" : "Football", 
    "ancestors" : [ 
        "Categories",  
        "Sports and fitness" 
     ],
     "parent" : "Sports and fitness" 
}

I have created a model and controller for the categories, and are as of now having problems querying the database.

This is the code in model/Category.js:

var mongoose = require('mongoose');

var Category = mongoose.Schema({
    _id: String
});

var categorySchema = mongoose.Schema({
    ancestors: [Category],
    parent: [Category]
});


//  Initiate database connection
var db = mongoose.createConnection('mongodb://localhost/Categories');
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
  console.log("openDB categories");
});

module.exports.category = db.model('Category', categorySchema);

This is the controller:

var categoryModel = require('../models/Category');
var Category = categoryModel.category;

exports.getAncestors = function(req, res) {
    if (req.params.id == undefined){res.send("no id specified!"); return;}

    Category.findOne({_id: 'Football'}, 'ancestors', function(err, ancestors){
        if(err) console.log(err);

        res.send(ancestors);
    });
}

When running this code I get the following error message:

{ message: 'Cast to ObjectId failed for value "Football" at path "_id"',
  name: 'CastError',
  type: 'ObjectId',
  value: 'Football',
  path: '_id' }

I believe the problem may be in the mongoose schema, but all help is greatly appreciated. Many thanks!

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Axelfran
  • 964
  • 1
  • 7
  • 17

1 Answers1

0

Mongoose tries to set an ObjectId by default. You can suppress this with the following:

var categorySchema = mongoose.Schema({
    _id: String,
    ancestors: [{type: String }],
    parent: {type: String}
},{ _id: false });

var Category = mongoose.model( "Category", categorySchema );

And noting that there is only one schema for you layout.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317