본문 바로가기

error records

[mongoDB/mongoose] Schema hasn't been registered for model / Populate

반응형

 

Schema hasn't been registered for model error cases below 

 

schema

const userSchema = new Schema<IUser>(
  {
    name: String,
    friends: [{ type: Schema.Types.ObjectId, ref: 'friends' }],
  },
  {
    timestamps: false,
    read: 'secondaryPreferred',
    versionKey: false,
  },
);

 

스키마 User에 friends라는 다른 모델을 Ref 해놓고 mongoose Populate를 하다가 나온 에러!

 

Wrong usage

const getFriends = async (userIdx, projection) => {
  return UserModel.find({userIdx},projection,{ lean: true })
  .populate({ path: 'friends');
};

const getFriends = async (userIdx, projection) => {
  return UserModel.find({userIdx},projection,{ lean: true })
  .populate({ path: 'friends', model: 'friends');
};

path에 user모델 필드인 friends를 적고 model을 안쓰면 위의 에러가 난다. 

또는 model을 string으로 써도 된다고 stackOverFlow에서 봤는데 나는 똑같은 에러가 났다. 

 

You will have the above error when you don't write the model name or in String. It should be brought (imported). 

 

Correct usage

import FriendsModel from somewhere

const getFriends = async (userIdx, projection) => {
  return UserModel.find({userIdx},projection,{ lean: true })
  .populate({ path: 'amountAdjustments', model: FriendsModel);
};

 

populate할 모델을 Import 해와서 사용하면 위의 에러가 사라지고 데이터가 잘 나온다! 

and now the data is corretly found and shown with populated data ! 

 

 

 

반응형