gpt4 book ai didi

node.js - 如何添加对模型的引用?

转载 作者:太空宇宙 更新时间:2023-11-03 23:59:34 24 4
gpt4 key购买 nike

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

还有其他事情...那么你能告诉我如何得到它吗?我是初学者,不太明白。

最佳答案

你可以这样做

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

关于node.js - 如何添加对模型的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55396606/

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