我正在為一個商店建立一個Mongoose模式
。我有兩個模式owner和shop,我正試圖在show中添加資料,并將ref作為所有者,但不知道如何做
這是我的模式結構
。const mongoose = require("mongoose"/span>) 。
var shopSchema = Schema({
位置。String,
startDate : Date,
endDate : 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)。
這就是我的模式的樣子,我試圖添加所有者和商店的細節,但不知道如何做到這一點,如果它是單一模式,我可以很容易地做到這一點,但對于ref,我不能
。const Owner = require(" 。 ./models/ownerSchema")。)
const addTask = async(req, res)=> {
let newOwmer = new Owner(req.body)。
try {
newOwner = await newOwner.save()。
cosnole.log("添加成功")。
} catch (err) {
console.log(err)。
}
};
我可以輕松地添加,但不知道如何添加商店
。uj5u.com熱心網友回復:
你必須要做這樣的事情
const mongoose = require("mongoose"/span>)。
var ownerSchema = Schema({
fname : String,
lname : String,
shopPlace : [{ type: Schema.Types.ObjectId, ref。'Shop' }] 。
});
var Owner = mongoose.model('Owner', ownerSchema)。
var shopSchema = Schema({
位置。String,
startDate : Date,
endDate : Date。
owner: Owner。
});
var Shop = mongoose.model('Shop', shopSchema) 。
當你創建一個商店時,先創建一個所有者,并在創建商店的時候添加所有者。也許像這樣
//匯入你的商店和所有者模型。
const fetchedOwner = await Owner.get('the-owner-id')
const createShop = {
位置。'倫敦'/span>
startDate : '某個日期'
結束日期。'另一個日期'。
owner: fetchedOwner
}
await Shop.create(createShop)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/319827.html
標籤:
上一篇:試圖使用GithubActions作業流將ReactApp部署到Azure,但在TypeScript中得到一個錯誤。
