看看以下架构:
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(唯一代码,因为它已经内置了Mongoose,所以优先使用objectID),所以如果我有以下代码:
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
答案 0 :(得分:3)
您可以通过为default
构造函数的activationId
字段定义ObjectId
属性来执行此操作:
var userSchema = new mongoose.Schema({
fullName: {
type: String,
required: true,
index: true
},
activationId: {
type: mongoose.Schema.ObjectId
default: mongoose.Types.ObjectId
}
});