views:

32

answers:

2

I've been trying to add to an array (or what ruby is saying is an array), but keep getting an error from mongo which says

Cannot apply $addToSet modifier to non-array

when I try to run

 
 User.collection.update({'id'=> current.id},{'$addToSet'=>{ 'following' => current.id}})
    User.collection.update({'id'=> user.id},{'$addToSet'=>{ 'following' => user.id}})

or the mongomapper version

User.push_uniq(current.id, :following => user.id)
    User.push_uniq(user.id, :followers => current.id)

When I output

<%= debug @user.following.kind_of? Array %>

returns true

However, when running

db.users.find() 

directly agains mongo, I get

{ "_id" : ObjectId("4c4a196f15a79004e0000007"), "email" : "[email protected]", "foll
owers" : null, "following" : null, "password_hash" : "98f2188de42bce1554d08fbc81
d5c99a2c234933", "password_salt" : "25d80a83cfe3d126cdbe9fec2b731ab9ea57c3b8", "
username" : "test" }

I would have expected following and followers to be [], not null.

When I output debug @user.followers, rails shows --- []

My model to create the user is

  key   :username,      :type => String
  key   :email,         :type => String
  key   :password_hash, :type => String
  key   :password_salt, :type => String
  key   :followers,     :type => Array
  key   :following, :type => Array

The error leads me to believe that the user.followers is being found, but can't be updated. When I change

 User.push_uniq(current.id, :testing => user.id)

I don't get an error, so I think i have that part right. Any suggestions?

A: 

Turns out this is a bit of an inconsistency with defining keys in mongomapper.

Don't use the :type => qualifier with Arrays.

I deleted the entire collection, removed :type, and recreated everything and now it works.

pedalpete
+1  A: 

This works for be in 0.8 when declaring the key using key :following, Array instead of key :following, :type => Array.

I tried both push_uniq and collection.update, and didn't get errors on either one. In your collection.update example, you do need to use _id: value instead of id: value since that command is being passed to mongo directly.

Emily