[英]How to write query value inside of query of mongoose
I have an array in mongo document as below.我在 mongo 文档中有一个数组,如下所示。
{
company: [
{name: "exist"},
{name: "cool"},
{name: "ho"}
]
}
And I want to get rid of a data in the array with position value.我想用 position 值删除数组中的数据。
So I made a query.所以我做了一个查询。
await Company.findOneAndUpdate({
_id: "xdef"
},
{
$unset: {
'company.1': 1
}
}
})
It works very well.它工作得很好。 And now,I want to put position by query.
现在,我想通过查询输入 position。
await Company.findOneAndUpdate({
_id: "xdef"
},
{
$unset: {
`company.{req.query.position}`: 1
}
}
})
But it gives me an error.但这给了我一个错误。 How can I make a code for this situation adequately?
我怎样才能充分地为这种情况编写代码?
Thank you so much for reading it.非常感谢您阅读它。
You can use the computed property names .您可以使用计算的属性名称。 And you are missing
$
also in the string literal.而且您在字符串文字中也缺少
$
。
await Company.findOneAndUpdate({
_id: "xdef"
}, {
$unset: {
[`company.${req.query.position}`]: 1
}
}
})
With Computed Property Names you can use an expression that will be computed as a property name on an object.
使用计算属性名称,您可以使用将作为 object 上的属性名称计算的表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.