尝试创建猫鼬模型实例时遇到与UUID相关的问题。
export interface IRessourceModel extends IRessource, mongoose.Document { }
export let RessourceSchema: mongoose.Schema = new Schema({
uuid: {
type: String,
default: uuidv4() },
name: {
type: String,
required: true,
minlength: RessourceValidation.CONSTANTS.NAME_MIN_LENGTH,
maxlength: RessourceValidation.CONSTANTS.NAME_MAX_LENGTH,
trim: true,
validate: {
validator: RessourceValidation.name,
message: '{VALUE} is not a valid name'}},
type: {
type: String,
required: true,
enum: RessourceValidation.ENUM.TYPE,
validate: {
validator: RessourceValidation.type,
message: '{VALUE} is not a valid type'}},
uploaded: {
type: Date,
required: true,
default: Date.now }
})
export const Ressource: mongoose.Model<IRessourceModel> = mongoose.model<IRessourceModel>('Ressource', RessourceSchema);
const RessourceModel = mongoose.model('Ressource');
// Some code here...
let Ressource: any = new RessourceModel({
name: req.body.name,
type: req.body.type,
})
Ressource.save((err, ressource) => {
if (err)
return (APIResponse.jsonErrorAfterMongooseQuery(res, 'Cannot create ressource', err));
APIResponse.json(res, ressource);
})
当我使用上述实例化代码在/ressources/
上发送POST请求时,将创建资源,但是,如果我发送另一个POST请求,则创建的第二个资源与UUID相同。第一个...
{
"type": true,
"data": {
"uuid": "1794bbb4-3385-4b0d-909a-e22c60aee608",
"_id": "5b3a42f5ae71a02af4ed6d11",
"name": "Name of ressource 1",
"type": "IMAGE",
"uploaded": "2018-07-02T15:21:25.866Z",
"__v": 0
}
}
{
"type": true,
"data": {
"uuid": "1794bbb4-3385-4b0d-909a-e22c60aee608",
"_id": "5b3a4530f3ab1f3d40b7ac93",
"name": "Name of ressource 2",
"type": "IMAGE",
"uploaded": "2018-07-02T15:30:56.379Z",
"__v": 0
}
}
我错误地使用了default: uuidv4()
还是它来自于我模仿猫鼬模型的方式?还是其他?
我确实尝试通过Schema.pre('save')
函数设置UUID,但没有成功...
我有点迷茫,感谢您的帮助!
答案 0 :(得分:0)
似乎uuidv4()
是一个字符串。当然,所有型号都相同。
考虑到这一点:
const uuidv4 = require('uuidv4');
猫鼬default
schema option can accept a function产生一个值:
export let RessourceSchema: mongoose.Schema = new Schema({
uuid: {
type: String,
default: uuidv4
},
...