node.js - 使用导入而不是 require() 时带有 uuid 的 MongooseError

标签 node.js typescript mongoose uuid nestjs

我收到以下错误:

MongooseError: document must have an _id before saving

当我尝试使用我的 API 使用 uuid 创建一个对象(Campagne)时:

import uuidv4 from 'uuid/v4';

它在我使用时有效:

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

我的 Campagne 对象使用其 uuid 正确创建。

这是我的对象架构的完整代码:

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 告诉我使用 import 而不是 require() 并在我的 IDE 中将其作为错误下划线,但它肯定无法正常工作,如上所示。

有人能解释一下为什么会这样吗?

有关信息,我将 NestJS node.js 框架与 Typescript 结合使用。

澄清:

我想知道为什么 importmongoose 有效,但对 uuid 无效(require正在为 uuid)

工作

最佳答案

我在 Github node-uuid 上找到了问题的答案。 以下代码正在运行:

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)

感谢您的回答。

关于node.js - 使用导入而不是 require() 时带有 uuid 的 MongooseError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52945342/

相关文章:

angularjs - Express Js/AngularJS cookie session 丢失

node.js - 在 Sails.js 中定义可重用函数的正确位置

Typescript 通用接口(interface)匹配属性值

javascript - 如何使用变量名创建字段?

node.js - Sequelize 不会将值插入到新添加的列中

reactjs - 你如何测试路由器与 jest 和 enzyme 的匹配参数?

typescript - 在 TypeScript 中分布式应用数组运算符

node.js - Push 或 addToSet 不适用于 Express、Node 和 mongoose(获取响应 { ok : 0, n : 0, nModified: 0 })

node.js - 为什么 mongoosastic 填充/ Elasticsearch 没有填充我的引用之一?我得到一个空对象

node.js - Puppeteer querySelector 返回 null