MongoDB save() method problem

Now, I am writing because I’ve got a small problem with insertion of the array into the database. It usually works, but not this time.

Here’s the test code:


<?php

require('../connection.php');
require('../session.php');
$entry = $collection->findOne(array("_id" => $_GET['id']));


$test = array( "comments" =>
  array(
  "_id" => new MongoId(),
  "comment" => "body",
  "author" => "maciejsitko",
  "date" => new MongoDate()
    )
  );
$entry->save($test);

?>

And this gives me:


Fatal error:
Call to a member function save() on a non-object

I know that my findOne() query finds a proper article by ‘_id’ because its present, and when I call something using the $entry cursors, it gives me content back.

What am I doing wrong that it doesnt save ? this should be dead simple and work, right?

you don’t call save() on the found entry, you call it on the collection. (i.e. PHP’s implementation doesn’t use chaining because it doesn’t work asynchronous (like the implementation in Node))

Oh Jesus Christ, you are right I need to Select the database and then save it by presenting the _id…

Thanks. I’m new to mongo still making loads of mistakes, think MySQLi is the way to go though. Just experimenting with it as its something new to me. Think I’ll make one blog on MongoDB and then I’m done with it ) But who knows.

The reason is there is not enough good and cheap hosting that supports it, especially in 64 bit way.

it should probably look more like

$entry = $collection->findOne(array("_id" => $_GET['id']));

// make sure $entry exists
$test = array( 
  "_id" => $entry["_id"],
  "comments" => array(
    "_id" => new MongoId(),
    "comment" => "body",
    "author" => "maciejsitko",
    "date" => new MongoDate()
  )
);
$collection->save($test);

for this operation it might be worth using update() and checking out the MongoDB update operators.

well, document-based databases play out their pull potential in languages, that are made for working with documents (e.g. JavaScript/MongoDB where a MongoDB result set is almost native to JS. you’ll find way more information for that combination).

But the thing is, with that solution, whether I try a normal update() without ‘upsert’ or save(), it does the same things; erases all my post data, after inserting the comments array. So, theres only ‘_id’ , and that ‘comments’ array, nothing else in the post that was there. How come?

allright, the key was $set parameter that avoids erasing all other data.

I usually use MongoDB with mongoose, then it’s simply a matter of actually pushing data onto the array.