简体   繁体   中英

Mongoose Node Js Join two collections

I am new to MEAN Stack and I am developing application using Node Js.

I have two collections say,

 var personSchema = Schema({ _id: Number, name: String, age: Number, stories: { type: Array, ref: 'Story' } }); var storySchema = Schema({ _creator: { type: Number }, story_id: String, fans: [{ type: Number }] }); var Story = mongoose.model('Story', storySchema); var Person = mongoose.model('Person', personSchema); 

In Person schema, the stories is a list of story_id which is an array of values. I need to list out all the persons data with their stories details also.

I have used, Person.find().populate("stories");
But it throws error,

{
  [CastError: Cast to ObjectId failed
    for value "26747261"
    at path "_id"
  ]
  message: 'Cast to ObjectId failed for value "26747261" at path "_id"',
    name: 'CastError',
    kind: 'ObjectId',
    value: 26747261,
    path: '_id',
    reason: undefined
}

Please help.

The reason you are getting the CastError is that you are not storing a list of story ids as you intended in the Person schema:

 var personSchema = Schema({
   ...
   stories : { type: Array, ref: 'Story' }
 });

Instead you should change it to:

 var personSchema = Schema({
   ...
   stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
 });

Also note the following (from Mongoose's documentation on population)

ObjectId, Number, String, and Buffer are valid for use as refs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM