[英]Mongoose auto increment a subdocuments field in array
I'm pushing subdocuments to an array:我正在将子文档推送到一个数组:
const deliverySchema = new db.Schema({
deliveryId: Number,
amountDelivered: Number,
price: Number
})
const suppliersSchema = new db.Schema({
supplierName: String,
phone: Number,
deliveries: [deliverySchema]
})
const delivery = {
"amountDelivered": 123,
"price": 123
}
Suppliers.updateOne(
{ _id: supplierId },
{ $push: { deliveries: delivery } }
)
How can I have the deliveryId
field inside that document auto increment on update.我怎样才能让该文档中的deliveryId
字段在更新时自动递增。 So the result would look something like:所以结果看起来像:
{
"supplierName": "Test supplier",
"phone": 12345678,
"deliveries": [
{
"deliveryId": 1, // Auto increment this field on update
"amountDelivered": 123,
"price": 123
},
{
"deliverId": 2,
"amountDelivered": 123,
"price": 1234
}
]
}
You can do it with Aggregation Framework:您可以使用聚合框架来做到这一点:
$concatArrays
- to concatenate the current deliveries array with new item $concatArrays
- 将当前交付数组与新项目连接起来$size
- to get the current size of the deliveries array $size
- 获取交付数组的当前大小$sum
- to sum current size of the deliveries array with 1 and use the result to set deliveryId $sum
-将 deliveries数组的当前大小与 1 相加并使用结果来设置deliveryIddb.collection.update({
"key": 1
},
[
{
"$set": {
"deliveries": {
"$concatArrays": [
"$deliveries",
[
{
"deliveryId": {
"$sum": [
1,
{
"$size": "$deliveries"
}
]
},
"amountDelivered": 123,
"price": 123
}
]
]
}
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.