[英]Can't push array in Mongoose subdocument
I'm trying to update an array by pushing it through findOneAndUpdate but I can't get it to update:我正在尝试通过 findOneAndUpdate 推送来更新数组,但我无法让它更新:
This is the code with which I try to push but does not make any movement:这是我尝试推送但不做任何动作的代码:
let pettyCashItem = await PettyCashItems.findOneAndUpdate({
_id: id,
"items._id": idItem },
{
$set: {
"items.$.concept": req.body.concept,
"items.$.incomeAmount": req.body.incomeAmount,
"items.$.description": req.body.description,
"items.$.expenseAmount": req.body.expenseAmount
$push: {
'items.$.lastModificationBy': {
"uid": req.uid,
"username": req.user.username,
"comments": req.body.comments
}
}
}
}, { new: 'true'});
This is my model:这是我的 model:
const PettyCashItemsSchema = Schema (
{
items:[{
concept: {
type: String,
maxlength:50,
required: [true, 'El Concepto es obligatorio']
},
incomeAmount:{
type: Number,
maxlength:50,
default:0,
required: [true, 'El Ingreso es obligatorio']
},
expenseAmount:{
type: Number,
maxlength:50,
default:0,
required: [true, 'El Egreso es obligatorio']
},
description: {
type: String,
maxlength:50,
required: [true, 'La Observación es obligatoria']
},
status: {
type: Boolean,
default: true,
required: [true, 'El Estatus es obligatorio']
},
createdAt: {
type: Date,
default: Date.now
},
lastModificationBy: [{
uid:{
type: String,
required:true
},
username:{
type: String,
required:true
},
date:{
type: Date,
default: Date.now
},
comments: {
type: String,
maxlength:300,
required: [true, 'El Comentario es obligatorio']
}
}]
}]
The update using $set for the other objects is correct but when trying to do a $push in the array this never works.对其他对象使用 $set 的更新是正确的,但是当尝试在数组中执行 $push 时,这永远不会起作用。
Thanks.谢谢。
Try placing $push
at same level with $set
instead of inner level of $set
.尝试将$push
与$set
放在同一级别,而不是$set
set 的内部级别。
let pettyCashItem = await PettyCashItems.findOneAndUpdate({
_id: id,
"items._id": idItem },
{
$set: {
"items.$.concept": req.body.concept,
"items.$.incomeAmount": req.body.incomeAmount,
"items.$.description": req.body.description,
"items.$.expenseAmount": req.body.expenseAmount
},
$push: {
'items.$.lastModificationBy': {
"uid": req.uid,
"username": req.user.username,
"comments": req.body.comments
}
}
}, { new: 'true'});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.