Search code examples
reactjsmongodbmongoosealgolia

How to define, append or map objectID to an array for Algolia?


In the docs, there is no example to explicitly define ObjectID. I do not want to use autoGenerateObjectIDIfNotExist as it duplicates my objects in the index. Nor do I want to use replaceAllObjects as creates more and more Indices each time.

I am using useEffect to pull the API from MongoDB. How would I define ObjectID by appending a custom ObjectID? Through afor loop?

For reference, this is for a MERN app.

If an ObjectID is not defined this error pops up:

"All objects must have an unique objectID (like a primary key) to be valid. Algolia is also able to generate objectIDs automatically but it's not recommended. To do it, use the {'autoGenerateObjectIDIfNotExist': true} option."


useEffect(() => {

    const config = {

      headers: {

        Authorization: `Bearer ${userInfo.token}`,

      },

    };

    const fetchPasswords = async () => {

      const { data } = await axios.get("/api/passwords", config);

      setPasswords(data);

    };

    fetchPasswords();

  }, []);
index

    .saveObjects(passwords, {

      objectIDs: passwords._id,

    })

    .then(({ objectIDs }) => {

      console.log(objectIDs);

    });

Solution

  • Once you get back the data. you can run a forEach through the array and replace the _id field with objectID field. After that setPasswords(data)
    For an example like this

    const data = [
    {
    _id: 1,
    password: 'password1'
    },{
    _id: 2,
    password: 'password2'
    },{
    _id: 3,
    password: 'password3'
    }
    ]
    
    data.forEach((password) => {
      password.objectID = password._id;
      delete password._id;
    })
    
    console.log(data);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

          const { data } = await axios.get("/api/passwords", config);
          //run the forEach for data.....
          setPasswords(data);
    

    Now that each record has an objectID you can index your data the usual way like

    index.saveObjects(passwords).then(({ objectIDs }) => {
      console.log(objectIDs);
    });
    

    You can do this like or you can set the objectID from the backend itself and send to frontend.