Jon Sud
Jon Sud

Reputation: 11641

mongoose populate array return empty results

How to populate the items array with full object?

This is what I try to do:

const documentCollection = await DocumentCollection.find({})
    .populate({ path: 'items', populate: { path: 'documents', model: 'Document' } });

But items fields is empty in documentCollection. why? not sure what I missing here

Here is the mongoose model:

export const DocumentsCollection = mongoose.model('Document-Collection',
  new mongoose.Schema({
    name: { type: String },
    items: [
      {
        name: { type: String },
        documents: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Document' }],
      },
    ],
  })
);

export const Document = mongoose.model( 'Document',
  new mongoose.Schema(
    {
      name: { type: String },
      description: { type: String }
    },
    { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' } }
  )
);

Upvotes: 0

Views: 70

Answers (2)

Shlomi Levi
Shlomi Levi

Reputation: 3305

Try this:

const documentCollection = await DocumentCollection.find({})
    .populate('items.documents');

Upvotes: 1

Moad Ennagi
Moad Ennagi

Reputation: 1073

I think you missed an 's' in documents.

const documentCollection = await DocumentCollection.find({})
    .populate({ path: 'items', populate: { path: 'documents', model: 'Document' } });

Upvotes: 0

Related Questions