Mongoose在架构中设置默认对象ID

时间:2014-11-21 09:51:39

标签: mongoose

我想在我的架构声明中执行此操作:

Member : { 
           type: mongoose.Schema.Types.ObjectId, 
           ref: 'otherMember', 
           default: ObjectId("123") 
         }

其中otherMember是其他实例化的Schema,其中包含ObjectId 123内的文档。

节点显示错误消息。如何实现?

2 个答案:

答案 0 :(得分:0)

当您将类型设置为 Schema.Types.ObjectId 时,您必须将默认值设置为字符串,并将其设置为作为ObjectId的参数给出,所以你的例子应该是:

Member : { 
           type: Schema.Types.ObjectId, 
           ref: 'otherMember', 
           default: '123' 
         }

答案 1 :(得分:0)

您可以尝试使用pre hook mongoose。喜欢这个

/* ECMASCript6 */

import mongoose from 'mongoose';
const SchemaTypes = mongoose.Schema.Types;

const YourSchema = new mongoose.Schema({
         roles: [{ //put your model field
            type: SchemaTypes.ObjectId,
            ref: 'Role'
           }]
  });
  

然后在预先挂钩:

  YourSchema.pre('save', (next) => {
  if(this.roles.length === 0){
    this.roles.push(new mongoose.Types.ObjectId("5962a5f37bde228394da6f72"))//this _id ref your model
  }
  next();//important!
});