如何 'join' 或填充数组
How to 'join' or populate an array
这是我最基本的产品架构:
const productSchema = new Schema({
productName: {
type: String,
required: true,
},
productDescription: {
type: String,
},
productPrice: {
type: Number,
},
});
module.exports = mongoose.model("Product", productSchema);
列出了这些产品,用户可以为每个产品添加数量。我按照下面的方式存储在一个对象数组中。我想将这两个集合连接在一起,以便输出用户选择的产品数量。我想我需要在这里使用 populate 但不确定如何设置 Refs 等等。
const PartySchema = new Schema({
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
catering: [{ id: mongoose.Types.ObjectId, qty: Number }],
created_at: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("Party", PartySchema);
我在假设餐饮领域是指向产品架构的 sub-document 数组的情况下共享此解决方案:
Product Schema 很好,所以它保持不变(尽管为了保持惯例,我建议将您的架构命名为 'Products' 而不是 'Product'、Mongo Naming Covention):
const productSchema = new Schema({
productName: {
type: String,
required: true,
},
productDescription: {
type: String,
},
productPrice: {
type: Number,
},
});
module.exports = mongoose.model("Products", productSchema);
接下来的 Party Schema 将是:
const PartySchema = new Schema({
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
catering: [{
id: {
type: mongoose.Types.ObjectId,
ref: 'Products',
},
qty: {
type: Number,
}
}],
created_at: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("Parties", PartySchema);
这是我最基本的产品架构:
const productSchema = new Schema({
productName: {
type: String,
required: true,
},
productDescription: {
type: String,
},
productPrice: {
type: Number,
},
});
module.exports = mongoose.model("Product", productSchema);
列出了这些产品,用户可以为每个产品添加数量。我按照下面的方式存储在一个对象数组中。我想将这两个集合连接在一起,以便输出用户选择的产品数量。我想我需要在这里使用 populate 但不确定如何设置 Refs 等等。
const PartySchema = new Schema({
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
catering: [{ id: mongoose.Types.ObjectId, qty: Number }],
created_at: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("Party", PartySchema);
我在假设餐饮领域是指向产品架构的 sub-document 数组的情况下共享此解决方案:
Product Schema 很好,所以它保持不变(尽管为了保持惯例,我建议将您的架构命名为 'Products' 而不是 'Product'、Mongo Naming Covention):
const productSchema = new Schema({
productName: {
type: String,
required: true,
},
productDescription: {
type: String,
},
productPrice: {
type: Number,
},
});
module.exports = mongoose.model("Products", productSchema);
接下来的 Party Schema 将是:
const PartySchema = new Schema({
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
catering: [{
id: {
type: mongoose.Types.ObjectId,
ref: 'Products',
},
qty: {
type: Number,
}
}],
created_at: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("Parties", PartySchema);