[英]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.