lua-resty-mongol icon indicating copy to clipboard operation
lua-resty-mongol copied to clipboard

insert an array but got nil element

Open pahud opened this issue 11 years ago • 2 comments

If I insert an array like this

col:insert({ {photos={"1","2"} } })

I'll get an null element like this { "_id" : ObjectId("536650e213cb857d4ebfd65c"), "photos" : [ null, "1", "2" ] }

Is this a bug?

pahud avatar May 04 '14 14:05 pahud

Hello, sorry for late update.

This issue due to the array index difference with lua and bson. The lua index starts from 1, but bson starts from 0. So if we insert an array by lua, the index 0 would be nil in the bson.

ashun's patch make the lua array index start from 0, the nil value disappeared, but the array count seem to be incorrected.

For example:

         col:insert({ {photos={"1","2"} } })
         r = col:find_one({})
         for i , v in pairs(r["photos"]) do
             ngx.say(i)
             ngx.say(v)
         end
         ngx.say(#r["photos"])

before patched, we get:

1
1
2
2
2 

After patched, we get:

0
1
1
2
1 

This issue lead by this problem which has been discussed in mongodb forum years ago : https://jira.mongodb.org/browse/SERVER-5908 I am not sure should we remove the nil value in the index 0 of the array. It seems there is a side effect.

bigplum avatar Jun 13 '14 05:06 bigplum

I tried to manually add a 0-tagged value, and shift all elements down to create a zero-based array. And it works fine.

Jeffwhen avatar Jul 20 '16 15:07 Jeffwhen