Mongoose在架构中设置默认对象id
我想在模式声明中执行此操作:Mongoose在架构中设置默认对象id,mongoose,Mongoose,我想在模式声明中执行此操作: Member : { type: mongoose.Schema.Types.ObjectId, ref: 'otherMember', default: ObjectId("123") } 其中,otherMember是另一个实例化的模式,其中包含ObjectId123文档 节点向我显示错误消息。如何实现?当您将类型设置为Schema.Types.ObjectId时,您必
Member : {
type: mongoose.Schema.Types.ObjectId,
ref: 'otherMember',
default: ObjectId("123")
}
其中,otherMember
是另一个实例化的模式,其中包含ObjectId123
文档
节点向我显示错误消息。如何实现?当您将类型设置为Schema.Types.ObjectId时,您必须将默认值设置为字符串,并且它作为ObjectId的参数提供,因此您的示例应该是:
Member : {
type: Schema.Types.ObjectId,
ref: 'otherMember',
default: '123'
}
你可以试试猫鼬。像这样
/* 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!
});