如何添加对模型的引用?

时间:2019-03-28 11:35:08

标签: node.js express mongoose

我是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;

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

2 个答案:

答案 0 :(得分:1)

您可以这样做

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
        })...

答案 1 :(得分:0)

尝试这样做:

async function(req, res){
    let newbranch = new Branch({
        branchName: "some value",
        officeTelephone: "some value",
        email: "some value",
        city: "some value",
        subCity: "some value",
        zone: "some value",
        wereda: "some value",
        kebele: "some value"
    });
    let branch = await newbranch.save();
    let branchId = branch._id;

    let newBloodStock = new BloodStock({
        bloodType: "some value",
        bloodAvailable: "some value",
        bloodUsed: "some value",
        branchId: branchId
    });
    let bloodStock = await newBloodStock.save();
    let findBloodStockData = await BloodStock.find({}).populate('branchId').exec()

}