在嵌套数组中使用$set
时,在mongodb/mongoose中使用$[<identifier>]
操作符有问题。当我使用它的时候,它似乎不工作,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" } }
如果我在{"index": 0}
中将0
更改为1
,则会出现此错误。我在store数组中只有一个对象,所以它在这里崩溃也就不足为奇了。
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' } ],
}
发布于 2020-08-19 17:15:39
the filtered positional operator的标识符部分用于根据子文档的字段指定条件。您的示例不起作用,因为没有用于存储的索引字段。
如果想要更新第一个元素,可以简单地使用点表示法:
{ $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);
});
https://stackoverflow.com/questions/63483533
复制相似问题