mongodb - 无法使用位置运算符
问题描述
在嵌套数组中$[<identifier>]
使用 mongodb/mongoose中的运算符时遇到问题。$set
使用它时似乎对我不起作用, item.nModified 始终为 0 并且数据库中没有任何更新。知道我做错了什么吗?
await Product.update(
{productName: product.productName},
{ "$set": {
"stores.$[index].trackingUrl": 'url',
} },
{ "arrayFilters": [
{ "index": 0 },
] },
).then((item) => {
console.log("Updated", item.nModified);
});
如果我删除 arrayFilters 对象并使用"stores.$[].trackingUrl": 'url'
, 没有运算符,它将正确更新值。
如果我使用"stores.$[].trackingUrl": 'url'
, 并离开 arrayFilters 我得到这个错误
MongoError: The array filter for identifier 'index' was not used in the update { $set: { stores.$[].trackingUrl: "url" } }
如果我将其更改0
为1
出现{"index": 0}
此错误。我目前在 stores 数组中只有 1 个对象,所以它在这里崩溃也就不足为奇了。
CastError: Cast to embedded failed for value "1" at path "stores"
架构Product
const ProductSchema = new Schema({
ean: String,
productName: String,
mainCategory: String,
subCategory: String,
group: String,
subSubCategory: String,
lowestPrice: Number,
isPopular: Boolean,
description: String,
keyword: String,
stores: [
{
name: String,
programId: Number,
productPrice: Number,
productUrl: String,
imageUrl: String,
sku: String,
currency: String,
manufacturerArticleNumber: String,
manufacturer: String,
oldPrice: Number,
shipping: Number,
inStock: Boolean,
market: String,
approvalStatus: Number,
trackingUrl: String,
productDescription: String,
timestamp: String,
},
],
});
一份文件
{ _id: 5f3bf084fa56743527344454,
ean: '000',
productName: 'name',
lowestPrice: 5,
mainCategory: 'Leksaker',
group: 'Leksaker',
subCategory: 'Djur',
subSubCategory: '',
stores:
[ { _id: 5f3cc819d28fc65d915016bc,
name: 'Stor & Liten',
programId: 0,
productPrice: 359,
productUrl: 'https://www.storochliten.se/papo-kaprosuchus',
imageUrl:
'https://media.storochliten.se/product-images/XL//papo-kaprosuchus-0.jpg',
sku: '317969',
currency: 'SEK',
manufacturerArticleNumber: 'P55056',
manufacturer: 'Papo',
oldPrice: 359,
shipping: 0,
inStock: true,
market: 'SE',
trackingUrl: '', //expect to insert "url" here
productDescription:'text',
timestamp: '2020-08-19T06:35:05.595Z' } ],
}
解决方案
过滤位置运算符的标识符部分用于指定基于子文档字段的条件。您的示例不起作用,因为没有用于存储的索引字段。
如果你想更新第一个元素,你可以简单地使用点符号:
{ $set: { 'stores.0.trackingUrl': 'url' }
如果您需要store
通过任何字段进行识别,您可以尝试使用_id
(或任何其他现有字段):
await Product.update(
{productName: product.productName},
{ "$set": {
"stores.$[store].trackingUrl": 'url',
} },
{ "arrayFilters": [
{ "store._id": 5f3cc819d28fc65d915016bc },
] },
).then((item) => {
console.log("Updated", item.nModified);
});
推荐阅读
- bixby - 如何将收集的值传递给重新计划的操作?
- python - 编写一个 python 代码,仅使用一个循环从列表中找出最大和第二个最大数
- r - R:在循环条件下引用不同列表元素中的var
- jquery - 覆盖不覆盖导航栏
- azure - 如何删除混合连接
- javascript - 如何在 React.js 中遍历来自 json 的对象数组
- python - 通过将其与传入记录进行比较来删除不断增长的数据库表中的重复记录 - Python
- http - 如何在 net/http 中为 HTTP2 配置帧大小
- python - 如果发生断开连接并在单独的文件中重新启动 main 方法,则希望引发异常。我应该如何实现这个?
- javascript - 如何在 Nestjs 中为第三方库创建自定义提供程序并访问请求和响应