BarthesSimpson
BarthesSimpson

Reputation: 954

how to stop rethinkdb converting object to array?

I'm very confused here. I'm passing an object called ScheduleAdd, and using insertAt to enter that object into an array called 'schedules' that exists in each document in the table 'teachers'. Rethink is throwing the error "Inserted value must be an OBJECT (got ARRAY)". It shows me an array that consists of my passed object with square brackets around it.

Code:

var scheduleAdd = {};
    scheduleAdd.schedule = name;
    scheduleAdd.visible = 'yes';
    console.log(scheduleAdd);  
r.db('test').table('teachers').update(function(teacher) {return teacher('schedules').insertAt(0,scheduleAdd)}).run(connection, function(err, result) {
    if (err) throw err;
    ;
    console.log('updated teacher schedules');
    console.log(result);
        });
     });

As an example, I might pass the object:

{ schedule: 'weekend', visible: 'yes' }

The console.log confirms that the object is well formed. However Rethink will then throw the error:

'Inserted value must be an OBJECT (got ARRAY):\n["{\\n  \\"schedule\\": \\"weekend\\",\\n      \\"visible\\": \\"yes\\"\\n}"]',

Any idea why my object is being converted into an array, and how I can stop it from happening? Thanks!

Upvotes: 2

Views: 348

Answers (1)

jek
jek

Reputation: 563

From the documentation, update 1 expects either an object or an expression returning an object, in your case you are passing in the expression:

function(teacher) {return teacher('schedules').insertAt(0,scheduleAdd)}

From the documentation as well, insertAt "returns the modified array" 2. This means that your expression is returning the new array of schedules rather than a object for the update. As a result, update ends up trying to insert an Array when it expects an Object. To demonstrate this, try running:

r.db('test').table('teachers').insert({schedules:[{name:"first"}]});
r.db('test').table('teachers').update(function(teacher) {return teacher('schedules').insertAt(0,{name:"second"})})

You will get the error:

Inserted value must be an OBJECT (got ARRAY):
[{
        "name": "second"
    }, {
        "name": "first"
    }]

The modified array with {"name":"second"} is correctly prepended to the existing schedules array from the row, and the new array is returned by insertAt. However, update cannot insert an array so the error is thrown.

To fix this, you could use:

r.db('test').table('teachers').update({schedules : r.row('schedules').insertAt(0,scheduleAdd)})

or

r.db('test').table('teachers').update(function(teacher) {return {schedules : teacher('schedules').insertAt(0,scheduleAdd)}})

Upvotes: 4

Related Questions