【问题标题】:MongooseError with uuid when using import instead of require()使用 import 而不是 require() 时带有 uuid 的 MongooseError
【发布时间】:2019-03-27 11:20:52
【问题描述】:

我收到以下错误:

MongooseError: document must have an _id before saving

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

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 中将其下划线作为错误,但它肯定无法如上所示工作。

谁能解释一下为什么会这样?

有关信息,我使用带有 Typescript 的 NestJS node.js 框架。

澄清:

我想知道为什么importmongoose 工作而不为uuid 工作(requireuuid 工作)

【问题讨论】:

    标签: node.js typescript mongoose uuid nestjs


    【解决方案1】:

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

    import {v4 as uuid} from 'uuid';
    

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

    import uuid from 'uuid/v4'; 语法不起作用,至少在 Node v10.9.0 上运行的 Typescript v3 项目中(没有 webpack 和 babel,只有 ts-node 来编译/运行 Typescript)

    我收到以下错误:TypeError: v4_1.uuid is not a function

    另一方面,import {v4 as uuid} from 'uuid'; 按预期工作

    (在uuid v3.3.2 上测试)

    感谢您的回答。

    【讨论】:

      【解决方案2】:

      删除_id: { type: String, default: uuidv4 },

      Mongoose 会自动生成_id

      并使用const ddd = require(...)

      我认为 ES6 模块在 Node 项目中无法正常工作

      【讨论】:

      • 但我想使用 uuid 而不是 Mongoose id
      • import 适用于我项目中除此之外的其他情况(例如猫鼬),为什么我需要在此特定情况下使用require()
      • @XavierFr 我认为这取决于库的模块结构。 github.com/kelektiv/node-uuid#readme库推荐CommonJS方式
      • 我明白了。我仍然不明白为什么它不能那样工作,但他们说要在 CommonJS 中那样做,所以我想我会遵循这个。如果有人能回答我为什么不能使用import,我会保持这个问题。
      猜你喜欢
      • 2021-11-01
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      • 2019-08-31
      • 2021-09-11
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多