Y
Y
Yaroslav2017-01-11 20:48:30
PHP
Yaroslav, 2017-01-11 20:48:30

How to make Backbone understand id mongodb?

How to make Backbone work with _id MongoDB?
So far I see two options:
1. Increment id in the process of creating a document, but due to access to the database by a large number of people, this increment must be kept separately, or even in Redis. It's a pain and an unnecessary bike.
2. The new mongo driver throws out a bunch of methods, including after insertOne it gives ->getInsertedId(). Alternatively, after creating the document, you can immediately find it and shove the parsed _id of the mongi into the forcibly created id field, but this is also a pain and an additional update request.
Maybe someone figured out the option with idAttribute: "_id" especially with put updates and delete destros?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yaroslav, 2017-01-13
@YarkoDzech

So so.
According to the thoughts that the comrades described above.
Based on the conditions that backEnd is the receiving side for changes in the database and nothing more, then:
Backbone GET
through find () we get a stack of documents, then through foreach we pack each document ($example) (or certain fields) into json, passing the id there which is equal to $example['_id']->__toString()
Backbone POST
when creating a document has a method to get its _id:
$example = $someCollection->insertOne(/../);
$idExample = $example->getInsertedId();
We pack the just received $idExample into the json that arrived to us, using the same method:
$idExample->__toString()
and send the json back to the backBone side
Backbone PUT and DELETE
An id arrives on the backEnd side as a string, repacking the string into an ObjectID
$input = json_decode(file_get_contents('php://input'));
$objId = new MongoDB\BSON\ObjectID($input->id);
* I did not find a regular method
And already on this $objId we update or delete the document
In principle .. for a bunch of crutch from several lines, without additional tambourines with increments or additional request-update.

L
lega, 2017-01-11
@lega

insertOne gives ->getInsertedId().
Instead, you need to create a new ObjectID () and specify it when saving to the database. In this case, you will have the final _id on hand before saving.
I don’t know what’s wrong with Backbone, but I passed both ObjectId and DBRef to the client as is, and used them on the client.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question