[英]Mongoose/MongoDB - Reference another Schema without ObjectId
我目前有两个架构。
var carSchema = new mongoose.Schema({
id: {
type: Number,
unique: true,
required: true
},
make: {
type: String,
required: true
},
model: {
type: String,
required: true
},
year: {
type: Number,
required: true,
min: config.MIN_YEAR,
max: config.MAX_YEAR
},
color: {
type: String
},
price: [
// don't know what to put here...
],
});
var priceSchema = new mongoose.Schema({
car_id: {
type: Number
},
amount: {
type: Number,
min: 0
},
year: {
type: Number,
min: config.MIN_YEAR,
max: config.MAX_YEAR
}
});
从上面的两个模式中可以看出,我正在尝试从汽车模式中引用价格模式。 我知道你可以通过引用ObjectId( _id
)来实现它,但我需要通过car_id
引用价格模式。 原因是因为我正在读取已经定义表头的CSV文件中的所有数据。 在猫鼬有没有可能的方法来做这个参考?
在汽车架构之上定义价格架构,然后将价格架构放入汽车架构。
...
color: {
type: String
},
price: [priceSchema]
...
你可以这样做:
var priceSchema = new mongoose.Schema({
car_id: {
type: Number
},
amount: {
type: Number,
min: 0
},
year: {
type: Number,
min: config.MIN_YEAR,
max: config.MAX_YEAR
}
});
然后将Price作为模型
var Price = mongoose.model('Price', priceSchema);
其次是:
var carSchema = new mongoose.Schema({
id: {
type: Number,
unique: true,
required: true
},
make: {
type: String,
required: true
},
model: {
type: String,
required: true
},
year: {
type: Number,
required: true,
min: config.MIN_YEAR,
max: config.MAX_YEAR
},
color: {
type: String
},
price: {
type: mongoose.Schema.Types.ObjectId, ref: 'Price'
},
});
然后将汽车模型设为:
var Car = mongoose.model('Car', carSchema);
这样就可以了。 然后,您可以将查询运行为:
Car.find({_id: 1})
.populate('price')
.exec(function(err, car) {
// do stuff with your car objects
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.