【发布时间】:2019-07-19 17:35:07
【问题描述】:
我有一个名为 authors 的集合,其架构如下:
authors: {
_id,
firstName,
lastName,
posts: [
post 1: {...},
post 2: {...},
post 3: {
_id,
title,
content,
tags: [
tag 1: {...},
tag 2: {...},
tag 3: {
_id,
name,
description,
},
],
},
],
}
可以看出,posts 是 authors 集合中的对象数组。该数组中的每个对象依次具有标签,即另一个对象数组。每个标签对象都有三个字段:_id、name和description。
我正在尝试编写一个 GraphQL 突变来更新集合中匹配文档的这个 name 字段。
const updatedTagInAuthor = await Author
.updateMany({ 'posts.tags._id': args.newTagInfo._id },
{
$set: {
'posts.$.tags.$.name': args.newTagInfo.name,
'posts.$.tags.$.description': args.newTagInfo.description,
},
}, opts);
上面的 sn-p 显然失败了,因为 MongoDB 不允许在查询中使用多个位置元素 ($)。那么是否有任何经济的替代方案来完成我想做的事情?
我尝试了 MongoDB 建议的 ArrayFilter 方法:
const updatedTagInAuthor = await Author.update(
{},
{ $set: { 'posts.$[].tags.$[tag].name': args.newTagInfo.name } },
{ arrayFilters: [{ 'tag._id': args.newTagInfo._id }], multi: true }
);
但这会引发以下错误:
无法读取未定义的属性“castForQuery”
还是一头雾水!
【问题讨论】:
标签: mongodb mongoose mongodb-query