Phie
Phie

Reputation: 413

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)

Upvotes: 4

Views: 1588

Answers (2)

Phie
Phie

Reputation: 413

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.

Upvotes: 3

ton1
ton1

Reputation: 7628

Remove _id: { type: String, default: uuidv4 },

Mongoose will automatically generate _id

And use const ddd = require(...)

I believe ES6 modules not working in Node project normally

Upvotes: 0

Related Questions