Javascript Mongoose JS路径默认生成id
请查看以下模式:Javascript Mongoose JS路径默认生成id,javascript,node.js,mongoose,Javascript,Node.js,Mongoose,请查看以下模式: var userSchema = new mongoose.Schema({ fullName: { type: String, required: true, index: true }, activationId: { type: mongoose.Schema.ObjectId } }); userSchema.path('activationId').default(function() { return new m
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
}
});