我有几个模型需要使用。但是,除非架构中存在唯一属性,否则模型不会作为文档添加到集合中。这发生在我的本地主机 mongo 和 mongo atlas 中。
每个具有具有唯一约束的属性的模型都会以正常方式添加。不会添加每个没有的模型。
当代码这样编写时,一切正常:
const UserSchema = new Schema ({
firstName: {
type: String,
required: [true, "firstName is required"]
},
lastName: {
type: String,
required: [true, "lastName is required"]
},
email: {
type: String,
required: [true, "email is required"],
index: { unique: true }
},
password: {
type: String,
required: [true, "password is required"]
},
appartments: [{
type: Schema.Types.ObjectId,
ref: "appartments"
}],
})
当电子邮件索引属性被注释掉时,文档将不会显示:
email: {
type: String,
required: [true, "email is required"]
//index: { unique: true }
},
我想将模型添加为文档,而无需在每个模型中设置唯一的约束。
所以我回来想通了!
显然,在从代码创建模型之前,模型不会添加为文档。因为用户架构已经从代码中添加了一个索引,所以它会创建。因此,要使您的模型作为集合可见,您需要执行以下操作:
Apartment.create({title: "My Apartment"})
.then(apartment => {
console.log("The apartment model is now visible with entry: " + apartment);
}).catch((error) => next(new ApiError(error, 400)))