gpt4 book ai didi

mongodb - Mongoose 填充数组

转载 作者:行者123 更新时间:2023-12-05 07:54:32 25 4
gpt4 key购买 nike

我无法让 Mongoose 填充对象数组。

架构如下:

var topOrganisationsForCategorySchema = new mongoose.Schema({
category: String,
topOrganisations: [{
organisation: {
type: mongoose.Schema.Types.ObjectId,
ref: 'organisation'
},
model: mongoose.Schema.Types.Mixed
}]
});

module.exports = mongoose.model('topOrganisationsForCategory', topOrganisationsForCategorySchema);

我希望这个集合中的所有对象都填充了一组组织。

这是我尝试过的

TopOrganisationsForCategory
.find()
.exec(function(err, organisation) {
var options = {
path: 'topOrganisations.organisation',
model: 'organisation'
};

if (err) return res.json(500);
Organisation.populate(organisation, options, function(err, org) {
res.json(org);
});
});

var organisationSchema = new mongoose.Schema({
name: String,
aliases: [String],
categories: [String],
id: {
type: String,
unique: true
},
idType: String
});

organisationSchema.index({
name: 'text'
});

module.exports = mongoose.model('organisation', organisationSchema);

最佳答案

你很接近,但有几个注意事项:

  • 以下代码假定您还具有 Oranisation 的架构/模型声明。
  • 我不确定 model 属性是作为一个选项(这将是无效的)还是实际上是 topOrganisations 的属性。

因此,我将 model 保留在其中,因为它不会引起任何问题,但请注意,如果您将它用作一个选项,它不会做您可能会做的事情认为是。

// Assuming this schema exists
var organisationSchema = new mongoose.Schema({...});

var topOrganisationsForCategorySchema = new mongoose.Schema({
category: String,
topOrganisations: [{
organisation: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Organisation' // Model name convention is to begin with a capital letter
}
// Is `model` supposed to be for the ref above? If so, that is declared in the
// Organisation model
model: mongoose.Schema.Types.Mixed
}]
});

// Assuming these model definitions exist
var Organisation = mongoose.model('Organisation', organisationSchema);
var TopOrganisationsForCategory = mongoose.model('TopOrganisationsForCategory', TopOrganisationsForCategorySchema);

// Assuming there are documents in the organisations collection

TopOrganisationsForCategory
.find()
// Because the `ref` is specified in the schema, Mongoose knows which
// collection to use to perform the population
.populate('topOrganisations.organisation')
.exec(function(err, orgs) {
if (err) {
return res.json(500);
}

res.json(orgs);
});

关于mongodb - Mongoose 填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31149179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com