[英]How do I create a oneToMany relationship between two Mongoose schemas?
我在同一目錄中的自己的 js 文件中有兩個模型。 一個叫做 Place(用於旅行清單應用程序),一個叫做 Country。 Country 將其國旗圖像的 URL 作為關鍵 flagURL。 我想用 Country 的 flagURL 值填充 Place 的“標志”鍵。 最好的方法是什么?
放置model
const mongoose = require('mongoose');
const placeSchema = new mongoose.Schema({
city: String,
country: String,
img: String, // this is for an image of the place, not the flag
flag: 'flagImg URL Here',
visited: Boolean,
});
const Place = mongoose.model('Place', placeSchema);
module.exports = Place;
國model
const mongoose = require('mongoose');
const countrySchema = new mongoose.Schema({
countryName: String,
countryCode: String,
flagImg: String
});
const Country = mongoose.model('Country', countrySchema);
module.exports = Country;
感謝您對我的初學者問題的幫助!
您必須在您的地點模式中引用國家模式(以便獲得與該特定地點相關聯的國家/地區)。
const mongoose = require('mongoose');
const placeSchema = new mongoose.Schema({
city: String,
img: String, // this is for an image of the place, not the flag
visited: Boolean,
country: {
type:mongoose.Schema.ObjectId,
ref: 'Country',
required: [true, 'A place must have a country']
}
});
const Place = mongoose.model('Place', placeSchema);
module.exports = Place;
country 屬性的作用是讓您訪問與特定地點相關的國家模式屬性的所有值。
你的有效載荷將是這樣的:
{
"city": "califonia",,
"img": dafault.png, // this is for an image of the place, not the flag
"visited": true,
"country": {
"countryName": "United States of America",
"countryCode": US,
"flagImg": dafault.png, // the country's flag
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.