0

My database has following type of documents for Categories collection.

{
    "_id" : ObjectId("56716afa403743492828aa07"),
    "cat_name" : "watches",
    "cat_parent_id" : [
        ObjectId("56716afa403743492828aa01"),
        ObjectId("56716afa403743492828aa03")
    ]
   .........
}

I first created database with Robomongo, then I'm trying to fetch data using mongoose and created following Schema.

var categorySchema = new Schema({
    'cat_name' : String,
    'cat_parent_id' : [{ type : mongoose.Types.ObjectId }],
    .......
});

but when I'm getting the result through following callback,

Categories.find(function(err,categories){........});

the cat_parent_id array is empty.

Edit:

When I replace mongoose.Types.ObjectId with Schema.Types.ObjectId or String,It works.Can anyone provide reason for that?

Sandeep Sharma
  • 1,855
  • 3
  • 19
  • 34
  • Shouldn't it be { type : [mongoose.Types.ObjectId] }? – PeterVC Dec 21 '15 at 13:12
  • 1
    Looks like a dupe of http://stackoverflow.com/questions/28617798/mongoose-schema-reference-and-undefined-type-objectid – JohnnyHK Dec 21 '15 at 14:07
  • The reason is that you need to use `mongoose.Schema.Types` to declare schema properties; `mongoose.Types` is meant for instantiation of particular types but is unrelated to schema setup. – robertklep Dec 22 '15 at 10:57

1 Answers1

0

You need to add reference for the ObjectId type:

var categorySchema = new Schema({
   'cat_name' : String,
   'cat_parent_id' : [{
              type: mongoose.Schema.Types.ObjectId,
              ref: 'Categories'
              }],
   .......
});
monali01
  • 160
  • 1
  • 9