Mongoose / MongoDB - 引用另一个没有ObjectId的Schema

时间:2017-07-02 11:19:42

标签: javascript node.js mongodb mongoose

我目前有两种模式。

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文件中的所有数据。 mongoose有没有可能的方法来提供这个参考?

2 个答案:

答案 0 :(得分:1)

在汽车架构之上定义价格架构,然后将价格架构放入汽车架构。

...
color: {
    type: String
},
price: [priceSchema]
...

答案 1 :(得分:0)

你可以这样做:

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
    }
 });

然后将价格模型设为

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
});