Generate Mongoose ObjectId in NextJs Frontend

Viewed 14

I am trying to generate Mongoose compliant ObjectId's on a NextJs frontend. The thing is though, the minute you import mongoose to try use the good-ol' const ObjectId = mongoose.Types.ObjectId; then const _id = new ObjectId(); 'maneuver' it immediately throws a TypeError: t.versions.node is undefined error in my case (very hard to debug the first time.. I was optimist it would work maybe this time doing some refactoring a few months later... But the minute I tried like oil in water.).

import mongoose from 'mongoose';
// and
const mongoose = require('mongoose');

Give the same error.

Is there a better way to create it? Other systems rely on this being a valid Id i.e. not just the same alphaNumeric length.

Less of a performance hit than creating a NextJs API GET route that just returns my backend shenanigans as a simple string (a network request?).

P.S. Use TypeScript if that could mean anything.. Also using Vercel (which has also caused build problems in the past)

1 Answers

I was too stuck in looking for a NextJs solution in my searches when it is still Javascript and React at the end of the day. This thread had the answer:

npm i bson

then

import { ObjectID } from 'bson';

const id  = new ObjectID();

Works perfectly in NextJs as well as my Mongo/Mongoose database.

Related