【问题标题】:Mongoose: how to redefine a schema programatically?Mongoose:如何以编程方式定义模式?
【发布时间】:2019-09-27 23:18:34
【问题描述】:

我有许多单独的 Mongoose 模式,它们通过 ObjecIds 相互引用。 基于这些,现在我想以编程方式编写另一个。

我尝试过类似以下的方法:

const Offers = require('../offers/offersModel')
const Stores = require('../stores/storesModel')

const flattenedStores = Stores.schema
const flattenedOffers = Offers.schema

// this step is not working as I expected
flattenedOffers.paths.storeId = flattenedStores 

const FeedsSchema = new Schema({ 
    offerId: flattenedOffers,
    // ...other fields
})

原来,在 Offers 模型中,storeId 是 ObjectId 引用 Stores 模型:

OffersSchema = new Schema({
    storeId : {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Stores',
        required: true
    },
    // ...other fields
})
module.exports = mongoose.model('Offers', OffersSchema)

我想以编程方式将其更改为子 flattenedStores 架构。但它没有用。该怎么做?

这个例子很简单,我确实可以在 FeedsSchema 中手动插入整个模式。但是,在我的实际用例中,存在一长串模式,每个模式都有许多字段,其中只有一个字段是对另一个模式的引用。

我宁愿只重新定义那些单一的引用,而不是手动将整个结构注入到 FeedsSchema 中……这可能吗?

【问题讨论】:

    标签: mongoose mongoose-schema


    【解决方案1】:

    所以,我找到了一种方法......将架构对象字段与构造的架构分开:

    const OffersSchemaObj = {
        storeId : {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Stores',
            required: true
        },
        // ...other fields
    }
    OffersSchema = new Schema(OffersSchemaObj)
    exports.model = mongoose.model('Offers', OffersSchema)
    exports.schema = OffersSchemaObj
    

    然后我可以使用架构对象并更改我想要的任何内容:

    const OffersSchema = require('../offers/offersModel').schema
    const StoresSchema = require('../stores/storesModel').schema
    
    OffersSchema.storeId = StoresSchema
    
    const FeedsSchema = new Schema({ 
        offerId: OffersSchema,
        // ...other fields
    })
    

    【讨论】:

      猜你喜欢
      • 2017-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-19
      • 2020-09-29
      • 2021-10-19
      • 2021-06-09
      • 2013-10-21
      相关资源
      最近更新 更多