我收到以下错误:
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 结合使用。
澄清:
我想知道为什么 import
对 mongoose
有效,但对 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 aTypescript v3
project running onNode v10.9.0
(without webpack nor babel, onlyts-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/