首页 > 解决方案 > 如何添加对模型的引用?

问题描述

我是 node js 的新手,我正在做一个项目。我想在另一个模型中引用一个模型。这些是模型

let mongoose = require('mongoose');

const bloodStockSchema = mongoose.Schema({
    bloodType: { type: String, required: true },
    bloodAvailable: { type: String, required: true },
    bloodUsed: { type: String, required: true },
    branchId: { type: mongoose.Schema.Types.ObjectId, ref: "Branch", required: true }}
});

module.exports = mongoose.model("BloodStock", bloodStockSchema);

这是另一个模型

const mongoose = require("mongoose");

const branchSchema = mongoose.Schema({
    branchName: { type: String, required: true },
    officeTelephone: { type: String, required: true },
    email: { type: String, required: true },
    city: { type: String, required: true },
    subCity: { type: String, required: true },
    zone: { type: String, required: true },
    wereda: { type: String, required: true },
    kebele: { type: String, required: true }
});

module.exports = mongoose.model("Branch", branchSchema);

我想要得到的是branchId. 这就是我试图得到它的方式:

let Branch = mongoose.model('Branch');
let branchId = Branch._id;

和另一个尝试:

let branchId = req.body.branchId;

还有另一件事......那么你能告诉我我是怎么得到它的吗?我是初学者,我不太清楚。

标签: node.jsexpressmongoose

解决方案


你可以这样做

let mongoose = require('mongoose');
let BloodStock = mongoose.model('BloodStock');
let BranchModel = mongoose.model('Branch');
let Branch = new BranchModel();

let bloodType = "some value";
let bloodAvailable = "some value";
let bloodUsed = "some value";
let branchId = mongoose.Types.ObjectId(Branch._id);

然后你可以调用create()方法来保存它。

BloodStock.create({
            bloodType: bloodType,
            bloodAvailable: bloodAvailable,
            bloodUsed: bloodUsed,
            branchId: branchId
        })...

推荐阅读