bwgjoseph / mongoose-vs-ottoman

feature comparison between mongoose and ottoman
0 stars 1 forks source link

using populate with select #98

Closed bwgjoseph closed 3 years ago

bwgjoseph commented 3 years ago

Hi,

How I do use populate with select?

This is the sample I used

const postSchema = new Schema({ title: String });
const commentSchema = new Schema({ text: String, post: { type: String, ref: 'post' }});

const postModel = model('post', postSchema);
const commentModel = model('comment', commentSchema);

const post = await postModel.create({ title: 'titleA' });
await commentModel.create({ text: 'commentA', post: post.id });

So I tried the following ways to do so but I think my syntax/usage are off

await commentModel.find({}, { populate: { populate: 'post', select: ['title'] } });
await commentModel.find({}, { populate: { populate: 'post', select: 'title' } });

It throws me this error

Unable to populate field "populate", it is not available on select clause [`text`, `post`, `id`]
Unable to populate field "select", it is not available on select clause [`text`, `post`, `id`]

And this is the output with the above method call

[
  _Model {
    id: 'a6d1faa5-a6c0-46aa-81aa-883664e7c451',
    post: '29c6d768-7ca0-4532-8da9-6f3bdf1daf6b',
    text: 'commentA'
  }
]

Thanks

bwgjoseph commented 3 years ago

I think this should be the correct syntax.

const { rows: populateB } = await commentModel.find({}, { populate: { post: { select: ['title', 'id'] }} });

Which gives me back

[
  _Model {
    id: 'b6eeee7a-0ca8-4832-a5f2-723c28047828',
    post: _Model {
      title: 'titleA',
      id: '49ced1c7-6296-4d76-bb7e-33b2163f9819'
    },
    text: 'commentA'
  }
]

Found on the docs-_populate which isn't very obvious/easy to find

AV25242 commented 3 years ago

Hello @bwgjoseph though I understand that you were not able to find it. I used https://ottomanjs.com/guides/document.html#using-population and then _populate link. I think the content is right there, may be an opportunity to re-arrange the docs might be required at some later point of time.

For now can we consider this issue to be closed ?

bwgjoseph commented 3 years ago

The question is not about how to populate but more about populating with select, so the link https://ottomanjs.com/guides/document.html#using-population won't work (or doesn't show it to use populate with select). You need to go https://ottomanjs.com/classes/document.html#populate which has more examples of how to get it work.

Which is why I don't see it the first time but subsequent dig into the doc got me there