Mongoose - using Populate on an array of ObjectId
Asked Answered
C

3

43

I've got a schema that looks a bit like:

var conversationSchema = new Schema({
    created: { type: Date, default: Date.now },
    updated: { type: Date, default: Date.now },
    recipients: { type: [Schema.ObjectId], ref: 'User' },
    messages: [ conversationMessageSchema ]
});

So my recipients collection, is a collection of object id's referencing my user schema / collection.

I need to populate these on query, so i'm trying this:

Conversation.findOne({ _id: myConversationId})
.populate('user')
.run(function(err, conversation){
    //do stuff
});

But obviously 'user' isn't populating...

Is there a way I can do this?

Corrincorrina answered 12/5, 2012 at 23:46 Comment(0)
J
44

Use the name of the schema path instead of the collection name:

Conversation.findOne({ _id: myConversationId})
.populate('recipients') // <==
.exec(function(err, conversation){
    //do stuff
});
Jotunheim answered 14/5, 2012 at 21:33 Comment(1)
my mongoose v5.11.14Ronn
S
125

For anyone else coming across this question.. the OP's code has an error in the schema definition.. it should be:

var conversationSchema = new Schema({
    created: { type: Date, default: Date.now },
    updated: { type: Date, default: Date.now },
    recipients: [{ type: Schema.ObjectId, ref: 'User' }],
    messages: [ conversationMessageSchema ]
});
mongoose.model('Conversation', conversationSchema);
Sestos answered 6/11, 2012 at 3:20 Comment(5)
You sir just saved me a world of pain. tips hatPapillose
Good way ! but how can you do an array of unique object id? With no duplicate?Byelaw
{ type: Schema.ObjectId, ref: 'User' , unique: true }Clientele
@MuliYulzary, I don't think that's right based on the docs right here. They claim it's not a validator but only helps in the creation of MongoDB indexes.Penna
not working. returning empty array. my mongoose v5.11.14Ronn
J
44

Use the name of the schema path instead of the collection name:

Conversation.findOne({ _id: myConversationId})
.populate('recipients') // <==
.exec(function(err, conversation){
    //do stuff
});
Jotunheim answered 14/5, 2012 at 21:33 Comment(1)
my mongoose v5.11.14Ronn
H
0

In my case I was using NestJS and I had schema Prop like this:

  @Prop({
    type: [{ type: Types.ObjectId, ref: 'Question' }],
    select: false,
  })
  // This shouldn't necessarily be Question[] as typescript cries
  questions: Types.ObjectId[] 

and changing this schema Prop to this resolved my issue:

  @Prop({
    type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Question' }],
    select: false,
  })
  questions: mongoose.Schema.Types.ObjectId[]
Hierolatry answered 12/7 at 10:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.