Mongoose uuid insted ObjectId

Mongoose uuid insted ObjectId

我想在 _id 字段中使用 uuid 字符串而不是 ObjectId。

models/user.js

var uuid = require('node-uuid');

var userSchema = mongoose.Schema({
    _id: {type: String, default: uuid.v4},
    nick: {type: String, unique : true, default: ""},
    email: {type: String, default: ""},
    pass: {type: String, default: ""},
    admin: {type: Boolean, default: false},
    created: {type: Date, default: Date.now},
    modified: {type: Date, default: Date.now}
});  

独特是必要的吗?

_id: {type: String, unique : true, default: uuid.v4},

UUID 根据定义是唯一的,因此您不一定需要将 _id 定义为在您的模型中是唯一的。