猫鼬查找,然后填充,然后重命名子文档
Mongoose find, then populate, then rename subdocument
如何在列表中填充索引,然后重命名其中一个索引?假设我有以下架构
const supplierSchema = new mongoose.Schema({
name: String,
address: String,
... (19 other fields)
supplier_id: mongoose.Schema.Types.ObjectId,
});
const itemsSchema = new mongoose.Schema({
name: String,
supplier_id: mongoose.Schema.Types.ObjectId,
item_id: mongoose.Schema.Types.ObjectId,
});
const receiptSchema = new mongoose.Schema({
items: [itemSchema]
receipt_id: mongoose.Schema.Types.ObjectId,
});
const Receipt = mongoose.model('Photo', photoSchema);
我的收据是这样填写的
Receipt.findById(<insertID>) currently gives:
{
receipt_id: ObjectId("..."),
items: [
{
name: "...",
supplier_id: ObjectId("..."),
item_id: ObjectId("...")
},
{
name: "...",
supplier_id: ObjectId("..."),
item_id: ObjectId("...")
}
],
receipt_id: ObjectId("..."),
}
我希望它用 name
和 address
填充 supplier_id
。然后将 supplier_id
重命名为 supplier
.
通过 $lookup
使用聚合
Receipt.aggregate([
{$match : {_id : <insertID>} },
{
$lookup : {
from: 'supplier',
localField: 'items.supplier_id',
foreignField: '_id',
as: 'supplier'
}
},
{
$unwind : {
path : "supplier"
}
}
])
如何在列表中填充索引,然后重命名其中一个索引?假设我有以下架构
const supplierSchema = new mongoose.Schema({
name: String,
address: String,
... (19 other fields)
supplier_id: mongoose.Schema.Types.ObjectId,
});
const itemsSchema = new mongoose.Schema({
name: String,
supplier_id: mongoose.Schema.Types.ObjectId,
item_id: mongoose.Schema.Types.ObjectId,
});
const receiptSchema = new mongoose.Schema({
items: [itemSchema]
receipt_id: mongoose.Schema.Types.ObjectId,
});
const Receipt = mongoose.model('Photo', photoSchema);
我的收据是这样填写的
Receipt.findById(<insertID>) currently gives:
{
receipt_id: ObjectId("..."),
items: [
{
name: "...",
supplier_id: ObjectId("..."),
item_id: ObjectId("...")
},
{
name: "...",
supplier_id: ObjectId("..."),
item_id: ObjectId("...")
}
],
receipt_id: ObjectId("..."),
}
我希望它用 name
和 address
填充 supplier_id
。然后将 supplier_id
重命名为 supplier
.
通过 $lookup
使用聚合Receipt.aggregate([
{$match : {_id : <insertID>} },
{
$lookup : {
from: 'supplier',
localField: 'items.supplier_id',
foreignField: '_id',
as: 'supplier'
}
},
{
$unwind : {
path : "supplier"
}
}
])