Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Mongo / BSON ObjectId with Parse Server

I currently have a project that's being migrated away from Parse Server but needs to maintain backwards compatibility.

Since Parse Server generates it's own object Ids, rather than using Mongo's I'd like to know:

  • How does Parse Server generate it's objectIds?

  • and why does it do this when MongoDB has great objectId generation natively?

  • Will parse be able to work with objects with non-Parse generated IDs?

An example:

_id: "LvIzxv5spL"                // created by Parse Server
_id: "507f1f77bcf86cd799439011"  // BSON.ObjectId created by MongoDB directly

Thanks for reading, any help would be greatly appreciated! Cheers :)

edited for brevity

like image 664
James Avatar asked Dec 04 '25 10:12

James


1 Answers

I found how the Parse Server generates a new Id on creation here. The comment documentation above states that the below function is getting called to generate a new id for Parse Server.

I still don't know why it has to create an id in its way rather than using Mongo's native one. It shall help to remove Parse Server dependency easily.

Please find the code below in c# that I am using to generate a new id like the parse server. I have not tested it with all aspects but, I think it will pass most if not all test cases of others.

    /// <summary>
    /// Randoms the string.
    /// </summary>
    /// <param name="length">The length.</param>
    /// <returns></returns>
    public static string RandomString(int length)
    {
        string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789";
        StringBuilder res = new();
        using (RNGCryptoServiceProvider rng = new())
        {
            byte[] uintBuffer = new byte[sizeof(uint)];

            while (length-- > 0)
            {
                rng.GetBytes(uintBuffer);
                uint num = BitConverter.ToUInt32(uintBuffer, 0);
                res.Append(chars[(int)(num % (uint)chars.Length)]);
            }
        }

        return res.ToString();
    }

    /// <summary>
    /// Gets the new object identifier.
    /// </summary>
    /// <param name="size">The size.</param>
    /// <returns></returns>
    public static string GetNewObjectId(int size = 10)
    {
        return RandomString(size);
    }

I hope this sample code helps recreate the logic in your preferred language.

like image 128
Rahul Mahadik Avatar answered Dec 07 '25 14:12

Rahul Mahadik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!