Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generate keywords from an array of object #11

Open
NohLokra opened this issue Jan 20, 2018 · 3 comments
Open

Generate keywords from an array of object #11

NohLokra opened this issue Jan 20, 2018 · 3 comments

Comments

@NohLokra
Copy link

Hi dude,

Awesome job on mongoose-keywords and all the other plugins you made for your rest api generator (querymen and bodymen are just... Waw 😃 )

But right now, in spite of all the awesomeness you've put in this, I'm getting stuck trying to get keywords from an array of objects that's inside my schema, here is some JSON of an object that I'd like to get keywords for:

{
    "name": "John",
    "pets": [{
        "name": "YellowBird",
        "kind": "bird"
    }, {
        "name": "PurpleDog",
        "kind": "dog"
    }]
}

I would like John's "keywords" field to be generated with ['john', 'bird', 'dog']. I tried many things like creating a petSchema but keywords get created inside pets objects and it seems like I can't access them because they are part of an object in an array.

Any clue would be really helpful since I couldn't find any on the Internet, I've been stuck for hours on this and that's the only blocking element that I met so far

Thanks for reading all of this, I hope my bad english is not making it too hard to understand :c
And of course, thanks for your help whenever you answer this 😄

@Juceztp
Copy link

Juceztp commented Nov 16, 2018

+1

@tlockcuff
Copy link

tlockcuff commented Jan 5, 2019

I was able to find away around this. It's not full-proof, but worked for my use case and may work for yours.

The transform function runs on every item in the "paths" array. You can check if the value is an object and then return the property off that object you want.

Here's some sample code:

SchemaNameHere.plugin(mongooseKeywords, {
  paths: ["name", "pets"],
  transform: value => {
    if (typeof value == "object" && value.hasOwnProperty("kind")) {
      return value.kind;
    }
    return value;
  }
});

That would save something like the following in the database:

{
  keywords: [
    'John',
    'bird',
    'dog'
  ]
}

Hopefully that helps!

@dfliess
Copy link

dfliess commented Apr 24, 2019

+1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants