Search code examples
arraysnode.jsmongooseschemaobjectid

NodeJS/Mongoose schema array of ObjectId


I am trying to implement an array of ObjectId inside a schema in Mongoose. I searched in internet and I found that this should work :

import mongoose from 'mongoose';
import Schema from 'mongoose';

const UserSchema = mongoose.Schema({
  nickName: {
    type: String,
    unique: true,
    required: true,
  },
  follows: [{
    type: Schema.Types.ObjectId, //HERE
    ref: 'User',
    default: []
  }],
}, {
  strict: true,
});

const User = mongoose.model('User', UserSchema);
export default User;

or this

follows: {
          type: [Schema.Types.ObjectId], // HERE
          ref: 'User',
          default: []
  },

I know they are not exactly the same, but instead of working in both cases I have this error :

 Invalid schema configuration: `ObjectID` is not a valid type within the array `follows`.

I don't know why is he telling my that ObjectID (with capital "ID") is not valid as I didn't declare any of this.

How can I do an array of objectId ? I want an array of ObjectId by reference of the schema "User" with the people an user follow

[EDIT] As Bhanu Sengar mentionned in the comment, I had to put "mongoose" before the Schema.

[{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }] 

As Halil SAFAK said, I deleted the default value.

It also didn't work because I had conflicts between the two imports

import mongoose from 'mongoose';
import Schema from 'mongoose';

Solution

  • I have used mongooose Populate property check my code. This will help you to understand.

    Category Schema

    const mongoose  = require('mongoose');
    const timestamps    = require('mongoose-timestamp');
    
    const cateorySchema = new mongoose.Schema({
      category_name: {
        type: String,
        trim: true,
        required: true,
      },
      active: {
            type: Boolean,
            default: true,
        }
    });
    
    cateorySchema.plugin(timestamps); // automatically adds createdAt and updatedAt timestamps
    module.exports = mongoose.model('Category',cateorySchema);
    

    SubCategory Schema

    'use strict'
    
    const mongoose    = require('mongoose');
    const timestamps    = require('mongoose-timestamp');
    
    const subCategorySchema = new mongoose.Schema({
        categories:{ type: mongoose.Schema.Types.ObjectId, ref: 'Category' },
        subcategorytitle:{
          type:String,
          trim:true,
          required: true
        },
        active: {
            type: Boolean,
            default: true
        }
    });
    subCategorySchema.plugin(timestamps); // automatically adds createdAt and updatedAt timestamps
    module.exports = mongoose.model('Subcategory',subCategorySchema);
    

    I hope this will help you. If you have any doubt let me know.