A
A
Andrew2019-01-21 23:40:20
Mongoose
Andrew, 2019-01-21 23:40:20

How does populate work in mongoose?

I create a simple chat.
There are three models: Users, Dialogs, Messages.
By analogy with populate in Waterline, I thought to build the following:
The database stores dialogs of the following form:
creator: '1';
members: ['1', '2']
The numbers are the user IDs from Users.
When searching through the database of dialogs, I wanted to immediately load the necessary data for users by these IDs, so I made the dialog model as indicated in the documentation:

var DialogSchema = new Schema({
  creator: String,
  members: [{type: Schema.Types.ObjectId, ref: 'User'}]
}

But apparently I'm missing something. I do a search on members, Dialog.find({members: req.params.id}), which, before trying to apply populate, returned the necessary dialogs to me. Now the error 'Cast to ObjectId failed for value "2" at path "members" for model "Dialog"' is returned . The value "2" is exactly the same user ID.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jekanok, 2020-06-10
@jekanok

How is it going? there is a solution,

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question