Mongodb update with arrayfilters | write exception: write errors: [Cannot apply array updates to non-array element groups: null]

huangapple go评论255阅读模式
英文:

Mongodb update with arrayfilters | write exception: write errors: [Cannot apply array updates to non-array element groups: null]

问题

我有以下的employee数据结构:

{
   "_id":{
      "$oid":"62836b0b3c1e2c19eaaac07e"
   },
   "firstname":"jean",
   "lastname":"paul",
   "email":"employee@test.co",
   "password":"d94307e0eabb9bba1ea1291e4b043175e11dcc43875a4858690e5c236b989f3e",
   "salt":"2CzpCiIbiyYcSxQ",
   "organizations":[
      {
         "organizationid":{
            "$oid":"62836aa93c1e2c19eaaac07d"
         },
         "organizationname":"test",
         "ismanager":false,
         "groups":[
            {
               "name":"mongroupe",
               "permissions":[
                  0,
                  2
               ]
            }
         ],
         "permissions":[
            1
         ]
      }
   ]
}

我正在尝试在Go中构建一个函数,将一组权限添加到organizations.[x].groups.[x].permissions数组中。每个permission都是一个简单的整数。

我想出了以下代码:

func AddPermissionsToGroup(groupName string, organizationId primitive.ObjectID, permissions []global.Permission) error {
	if res, err := employeesCollection.UpdateMany(
		context.TODO(),
		bson.M{},
		bson.M{
			"$addToSet": bson.M{
				"organizations.$[org].groups.$[grp].permissions": bson.M{
					"$each": permissions,
				},
			},
		},
		options.Update().SetArrayFilters(
			options.ArrayFilters{
				Filters: []interface{}{
					bson.M{
						"org.organizationid": organizationId,
					},
					bson.M{
						"grp.name": groupName,
					},
				},
			},
		),
	); res.MatchedCount == 0 {
		return global.ErrEntityNotFound
	} else if res.ModifiedCount == 0 {
		return global.ErrNoUpdateNeeded
	} else if err != nil {
		return fmt.Errorf("failed updating employees | %s", err.Error())
	}
	return nil
}

代码返回以下错误:write exception: write errors: [Cannot apply array updates to non-array element groups: null]。

我不知道这是什么意思。

也许引擎不喜欢我使用两个ArrayFilter

英文:

I have the following employee data structure :

{
   "_id":{
      "$oid":"62836b0b3c1e2c19eaaac07e"
   },
   "firstname":"jean",
   "lastname":"paul",
   "email":"employee@test.co",
   "password":"d94307e0eabb9bba1ea1291e4b043175e11dcc43875a4858690e5c236b989f3e",
   "salt":"2CzpCiIbiyYcSxQ",
   "organizations":[
      {
         "organizationid":{
            "$oid":"62836aa93c1e2c19eaaac07d"
         },
         "organizationname":"test",
         "ismanager":false,
         "groups":[
            {
               "name":"mongroupe",
               "permissions":[
                  0,
                  2
               ]
            }
         ],
         "permissions":[
            1
         ]
      }
   ]
}

I'm trying to build a function in go that adds a set of permissions to the organizations.[x].groups.[x].permissions array. Each permission is a simple integer.

I've come up with the following code :


func AddPermissionsToGroup(groupName string, organizationId primitive.ObjectID, permissions []global.Permission) error {
		if res, err := employeesCollection.UpdateMany(
		context.TODO(),
		bson.M{},
		bson.M{
			"$addToSet": bson.M{
				"organizations.$[org].groups.$[grp].permissions": bson.M{
					"$each": permissions,
				},
			},
		},
		options.Update().SetArrayFilters(
			options.ArrayFilters{
				Filters: []interface{}{
					bson.M{
						"org.organizationid": organizationId,
					},
					bson.M{
						"grp.name": groupName,
					},
				},
			},
		),
	); res.MatchedCount == 0 {
		return global.ErrEntityNotFound
	} else if res.ModifiedCount == 0 {
		return global.ErrNoUpdateNeeded
	} else if err != nil {
		return fmt.Errorf("failed updating employees | %s", err.Error())
	}
	return nil

}

The code returns the following error : write exception: write errors: [Cannot apply array updates to non-array element groups: null].

I have no idea what it means.

Maybe the engine doesn't like the fact that I use two ArrayFilters ?

答案1

得分: 1

好的,以下是翻译好的内容:

好的,我创建了一个可以工作的游乐场:https://mongoplayground.net/p/Tznz7btfLkH

实际上,问题并不是因为请求本身的语法有效性问题。问题出在我在employee集合中有另一个文档,它看起来像这样:

{
   "id":{
      "$oid":"62836aa93c1e2c19eaaac07c"
   },
   "firstname":"jean",
   "lastname":"charles",
   "email":"manager@test.co",
   "password":"6776c354fce809e7be234f84d0ea907cfd3aba350871a18858ceccc10eabc036",
   "salt":"IHaPJIKVVplC8ni",
   "organizations":[
      {
         "organizationid":{
            "$oid":"62836aa93c1e2c19eaaac07d"
         },
         "organizationname":"test",
         "ismanager":true,
         "groups":null,
         "permissions":null
      }
   ]
}

如你所见,这里的groups值为null。这就是问题所在。

基本上,当名为grp的数组过滤器遇到一个null对象时,它会引发错误,因为无法对其应用。

所以,使请求正常工作的解决方案是确保集合中的每个文档都初始化了这个group数组(即使它是空的也没关系)。一旦我这样做了,就没有问题了。

英文:

Ok so i created this playground that works : https://mongoplayground.net/p/Tznz7btfLkH

Actually the issue was not because of the request itself that was valid syntaxically. It came from the fact i had another document in the employee collection that looked like this :

{
   "_id":{
      "$oid":"62836aa93c1e2c19eaaac07c"
   },
   "firstname":"jean",
   "lastname":"charles",
   "email":"manager@test.co",
   "password":"6776c354fce809e7be234f84d0ea907cfd3aba350871a18858ceccc10eabc036",
   "salt":"IHaPJIKVVplC8ni",
   "organizations":[
      {
         "organizationid":{
            "$oid":"62836aa93c1e2c19eaaac07d"
         },
         "organizationname":"test",
         "ismanager":true,
         "groups":null,
         "permissions":null
      }
   ]
}

As you can see, the groups value is null here. And that is the problem.

Basically, when the arrayfilter named grp meets a null object, it raises an error because it can't apply on it.

So the solution to make the request work was to make sure every document in the collection had this group array initialized (even if it's empty, it doesn't matter). Once I did this there was no problem anymore.

huangapple
  • 本文由 发表于 2022年5月17日 21:14:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/72274734.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定