0

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)

Tribe56123
  • 382
  • 1
  • 15
Tumo Masire
  • 422
  • 5
  • 10
  • Yes, I am aware that the issue is that node is note exactly available on a frontend browser. Just asking for workarounds, help, or advice. – Tumo Masire Sep 14 '22 at 22:50

1 Answers1

0

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 Next.js as well as my Mongo database / Mongoose.

Community
  • 1
  • 1
Tumo Masire
  • 422
  • 5
  • 10