node.js - 如何添加对模型的引用?
问题描述
我是 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
})...
推荐阅读
- python - 如何获取使用 schema_editor 动态创建的 django 模型?
- c++ - 将向量转换为数组列表
- c++ - 当没有明确的输入结束时从标准输入读取 C++
- javascript - 如何检查对象值是否等于数组中的字符串?
- python - 在 Windows 上运行 python 模块命令
- javascript - 特定属性的猫鼬查询
- python - 为什么使用全局部分时 AWS SAM CLI (awssamcli) 无法构建?
- javascript - pdf 打印了不寻常的字符。jsPDF
- firebase-authentication - Does Google Identity Platform support encrypted SAML assertion?
- javascript - 将 response.data.data 从 api 转换为结构化对象 vue js