Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Mongoose JS路径默认生成id_Javascript_Node.js_Mongoose - Fatal编程技术网

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
  }
});