看看下面的架构:
var userSchema = new mongoose.Schema({
fullName: {
type: String,
required: true,
index: true
},
activationId: {
type: mongoose.Schema.ObjectId
}
});
userSchema.path('activationId').default(function() {
return new mongoose.Schema.ObjectId.fromString('actvt');
});
这是关于“activationId”的,我想在创建用户后生成一个 ID(唯一代码,首选 objectID,因为它已经内置在 Mongoose 中),所以如果我有以下代码:
var newUser = new User({
fullName: 'Rick Richards'
});
newUser.save(function(error, data){
console.log(data.activationId); // Should give the activationId
});
但是这个解决方案给我以下错误:
TypeError: undefined is not a function
最佳答案
您可以通过为 activationId
字段定义一个 default
属性来做到这一点,该字段是 ObjectId
构造函数:
var userSchema = new mongoose.Schema({
fullName: {
type: String,
required: true,
index: true
},
activationId: {
type: mongoose.Schema.ObjectId
default: mongoose.Types.ObjectId
}
});
关于javascript - Mongoose JS路径默认生成id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13635114/