gpt4 book ai didi

node.js - Mongoose 中的一对多关系

转载 作者:太空宇宙 更新时间:2023-11-04 02:48:20 25 4
gpt4 key购买 nike

我正在使用平均堆栈创建一个混合应用程序。我正在使用 nosql 在 mongoose 中创建数据库。我的数据库由两个表组成,一个是“donors”,另一个是“bloodGroup”。我的“bloodGroup”架构如下:

module.exports = function(mongoose) {
var Schema = mongoose.Schema;

/* bloodGroup Schema */
var bloodGroupSchema = new Schema({
name: { type: String, required: true }
});
}

我的“捐助者”架构如下:

/* Donor Schema */
var DonorSchema = new Schema({
Name: { type: String, required: true },
DOB: { type: Date, required: true, trim: true },
Sex: { type: String },
BloodGroupID: { type: Schema.Types.ObjectId, ref: 'BloodGroup', required: true },
ContactNo: { type: String, required: true },
LocationId: { type: Schema.Types.ObjectId, ref: 'Location', required:true },
EmailId: { type: String, required: true },
Password: { type: String, required: true }
});

当许多献血者引用单一血型时,会报告 BloodGroup 对象 ID 错误。如何解决此问题?

最佳答案

您可以引用此链接获取文档:http://mongoosejs.com/docs/populate.html

Saving Refs

    /* Donor Schema */
var DonorSchema = new Schema({
_id : {type: Number},
Name: { type: String, required: true },
DOB: { type: Date, required: true, trim: true },
Sex: { type: String },
BloodGroupID: { type: Schema.Types.ObjectId, ref: 'BloodGroup', required: true },
ContactNo: { type: String, required: true },
LocationId: { type: Schema.Types.ObjectId, ref: 'Location', required:true },
EmailId: { type: String, required: true },
Password: { type: String, required: true }
});


/* bloodGroup Schema */
var bloodGroupSchema = new Schema({
_bid :{ type: Number, ref: 'Donor' },
name: { type: String, required: true }
});


module.exports = mongoose.model('Donor', DonorSchema);
module.exports = mongoose.model('Blood', bloodGroupSchema);


var vidya = new Donor({ _id: 0, name: 'Vidya', sex: 'F' });
vidya.save(function (err) {
if (err) return handleError(err);

var blood = new BloodGroup({
name: 'B+',
_bid: vidya._id // assign the _id from the Donor
});

blood.save(function (err) {
if (err) return handleError(err);
// thats it!
});
});

关于node.js - Mongoose 中的一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36974948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com