Skip to content

[3.x] fix truncate to delete items in collection #1993

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jul 22, 2020
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 4 additions & 9 deletions src/Jenssegers/Mongodb/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Jenssegers\Mongodb\Connection;
use MongoCollection;
use MongoDB\BSON\Binary;
use MongoDB\BSON\ObjectID;
use MongoDB\BSON\Regex;
Expand All @@ -20,7 +19,7 @@ class Builder extends BaseBuilder
{
/**
* The database collection.
* @var MongoCollection
* @var \MongoDB\Collection
*/
protected $collection;

Expand Down Expand Up @@ -698,15 +697,11 @@ public function from($collection, $as = null)
/**
* @inheritdoc
*/
public function truncate()
public function truncate(): bool
{
$options = [
'typeMap' => ['root' => 'object', 'document' => 'object'],
];

$result = $this->collection->drop($options);
$result = $this->collection->deleteMany([]);

return (1 == (int) $result->ok);
return (1 === (int) $result->isAcknowledged());
}

/**
Expand Down
4 changes: 3 additions & 1 deletion tests/QueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,10 @@ public function testDelete()
public function testTruncate()
{
DB::collection('users')->insert(['name' => 'John Doe']);
DB::collection('users')->insert(['name' => 'John Doe']);
$this->assertEquals(2, DB::collection('users')->count());
$result = DB::collection('users')->truncate();
$this->assertEquals(1, $result);
$this->assertTrue($result);
$this->assertEquals(0, DB::collection('users')->count());
}

Expand Down