我有许多单独的Mongoose模式,它们之间用ObjecId
相互引用。
基于这些,现在我想以编程方式编写另一个。
我尝试了以下操作:
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
})
最初,在“优惠”模型中,storeId是引用商店模型的ObjectId:
OffersSchema = new Schema({
storeId : {
type: mongoose.Schema.Types.ObjectId,
ref: 'Stores',
required: true
},
// ...other fields
})
module.exports = mongoose.model('Offers', OffersSchema)
我想以编程方式将其更改为sub flattenStores模式。但这没有用。该怎么做?
这个例子很简单,我确实可以将整个模式手动插入FeedsSchema中。但是,在我的实际用例中,存在很长的架构链,每个架构都有许多字段,其中只有一个字段是对另一个架构的引用。
我宁愿只重新定义那些单个引用,而不是将整个结构手动注入FeedsSchema中……有可能吗?
答案 0 :(得分:1)
因此,我找到了一种解决方法...将架构对象字段与构造的架构分开:
struct datastructure
{
struct iterator
{
virtual std::unique_ptr<datastructure::iterator> operator++(void) = 0;
virtual std::unique_ptr<datastructure::iterator> operator++(int) = 0;
}
virtual std::unique_ptr<iterator> begin(void) const = 0;
}
然后,我可以使用架构对象并更改所需的内容:
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