将特定属性引用到猫鼬中的另一个模式

问题描述 投票:0回答:1

我可以知道如何引用特定字段吗,比如在我的代码中是 flowerName?我想将 flowerName 引用到 stockSchema 中的 inventorySchema。这行得通吗?


const inventorySchema = ({
    id: {type: mongoose.Schema.Types.ObjectId, ref: 'Stocks', required: true},

    flowerName: {ref: 'Stocks', required: true},

    orderName: {
        type: String,
        required: true
    }
})


module.exports = mongoose.model('Inventory', inventorySchema);
const stockSchema = new Schema({
    id: {
        type: Number
    },
    flowerName: {
        type: String,
        required: true
    }
module.exports = mongoose.model('Stocks', stockSchema);

node.js database express mongoose schema
1个回答
0
投票

你应该参考库存

const inventorySchema = new Schema({
  orderName: {
    type: String,
    required: true,
  },
  flowerName: {
    type: String,
    required: true,
  },
});

module.exports = mongoose.model('Inventory', inventorySchema);

const stockSchema = new Schema({
    id: {
        type: Number
    },
    inventory: {
        type: Schema.Types.ObjectId,
        ref: 'Inventory',
        required: true
    }
});

module.exports = mongoose.model('Stocks', stockSchema);

然后您应该能够通过使用以下内容填充库存实例来引用

flowerName

const stock = Stocks.findOne({}).populate('inventory').exec();
if (stock) stock.inventory.flowerName
© www.soinside.com 2019 - 2024. All rights reserved.