Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongooseError with uuid when using import instead of require()

I get the following error :

MongooseError: document must have an _id before saving

When I try to create an Object (Campagne) with uuid with my API using :

import uuidv4 from 'uuid/v4';

It works when I use :

const uuidv4 = require('uuid/v4');

My Campagne object is created correctly with its uuid.

Here is the full code of my object's Schema :

import * as mongoose from 'mongoose';
import uuidv4 from 'uuid/v4';

export const CampagneSchema = new mongoose.Schema({
    _id: { type: String, default: uuidv4 },
    dateDebut: Date,
    dateFin: Date,
    reduction: Number,
});

TSLint tell me to use import instead of require() and underline it as an error in my IDE but it's definitely not working as shown above.

Can someone explain me why is this happening please ?

For information, I use the NestJS node.js framework with Typescript.

To clarify :

I want to know why import is working for mongoose but not for uuid (require is working for uuid)

like image 728
Phie Avatar asked Aug 30 '25 16:08

Phie


1 Answers

I found the answer with an issue on Github node-uuid. The following code is working :

import {v4 as uuid} from 'uuid';

https://github.com/kelektiv/node-uuid/issues/245

import uuid from 'uuid/v4'; syntax does not work, at least in a Typescript v3 project running on Node v10.9.0 (without webpack nor babel, only ts-node to compile/run Typescript)

I get the following error: TypeError: v4_1.uuid is not a function

on the other hand, import {v4 as uuid} from 'uuid'; works as expected

(tested on uuid v3.3.2)

Thanks for the answers.

like image 51
Phie Avatar answered Sep 02 '25 05:09

Phie