javascript - 如何在猫鼬的另一个方案中添加参考和数据
问题描述
我正在为商店构建 Mongoose 模式
我有两个架构owner
,shop
我正在尝试以 ref 作为所有者在 show 中添加数据,但不知道该怎么做
这是我的架构结构
const mongoose = require("mongoose");
var shopSchema = Schema({
location : String,
startDate : Date,
endDate : Date
});
var ownerSchema = Schema({
fname : String,
lname : String,
shopPlace : [{ type: Schema.Types.ObjectId, ref: 'Shop' }]
});
var Shop = mongoose.model('Shop', shopSchema);
var Owner = mongoose.model('Owner', ownerSchema);
所以这就是我的架构的样子,我正在尝试添加所有者和商店的详细信息,但如果它是单一架构我不知道该怎么做我可以轻松地做到这一点,但使用参考我不能
const Owner = require("../models/ownerSchema");
const addTask = async (req, res) => {
let newOwmer = new Owner(req.body);
try {
newOwner = await newOwner.save();
cosnole.log("Added Successfully");
} catch (err) {
console.log(err);
}
};
我可以轻松添加但不知道如何添加商店
解决方案
你必须做这样的事情
const mongoose = require("mongoose");
var ownerSchema = Schema({
fname : String,
lname : String,
shopPlace : [{ type: Schema.Types.ObjectId, ref: 'Shop' }]
});
var Owner = mongoose.model('Owner', ownerSchema);
var shopSchema = Schema({
location : String,
startDate : Date,
endDate : Date,
owner: Owner
});
var Shop = mongoose.model('Shop', shopSchema);
然后在创建店铺的时候,先创建一个店主,在创建店铺的时候添加店主。也许像这样
// Import your shop and owner models
const fetchedOwner = await Owner.get('the-owner-id')
const createShop = {
location : 'London'
startDate : 'some date'
endDate : 'another date'
owner: fetchedOwner
}
await Shop.create(createShop)
推荐阅读
- qemu - qemu-riscv 如何将设备树 Blob 传递给来宾内核?
- c# - 人工智能书籍内容分类
- lighthouse - 如何修复 Lighthouse “提供低分辨率图像”
- javascript - React 本机钩子不会重新加载信息
- haskell - 使用 try 将 String 转换为 Float
- flutter - 流式传输开始时间问题 - Flutter
- c# - 带有连接查询的自动映射器
- c++ - 在 initializer_list 参数的情况下如何调用 std::make_shared?
- c - if else 语句的 else 部分不起作用
- postgresql - pg_upgrade --link 在将 Postgres 从 10.9 升级到 12.2 时失败