I have an application using Vue Laravel and I am using mysql database. Now, I need to use mongodb database too.
So, here is my live mongodb database table (projects) and collection (product_1, product_2 etc...)
Like this:
Now, I want to get all the collection. To do that I have created Model called Import
Import.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Jenssegers\Mongodb\Eloquent\Model;
class Import extends Model
{
protected $connection = 'mongodb';
protected $collection = 'projects';
}
and created a controller called ImportController.php.
ImportController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Import;
class ImportController extends Controller
{
public function show_import () {
$all_import = Import::all();
return response()->json( $all_import, 200);
}
}
.env file
MONGO_DB_HOST=107.200.220.71
MONGO_DB_PORT=57019
MONGO_DB_DATABASE=projects
MONGO_DB_USERNAME=marketplus_pr
MONGO_DB_PASSWORD="my-password"
database.php
'mongodb' => [
'driver' => 'mongodb',
'dsn' => 'mongodb srv://marketplus_pr:[email protected]/projects?retryWrites=true&w=majority',
'database' => 'projects'
],
Now using this api route call:
http://localhost:3000/api/projects/import/show-import/343-3-3-3-3
I am getting this message:
{"success":false}
But Its should give me all the collection, right?
Can you tell me what I am doing wrong here?
CodePudding user response:
Your request is being intercepted by a different route declaration / controller. (chat reference) Also, wrong collection name.
You should make a few changes in the api.php file:
Move this route declaration:
Route::get('projects/import/show-import/{token}', [App\Http\Controllers\ImportController::class, 'show_import'])->name('show_import');
just after:
Route::group([], function ($router) {
making it as:
Route::group([], function ($router) {
Route::get('projects/import/show-import/{token}',
[App\Http\Controllers\ImportController::class, 'show_import'])-
>name('show_import');
...
}
also, the {token}
URL parameter makes not sense so you should remove it.
and, change the collection name to products_1
in the Import.php
model file:
class Import extends Model
{
protected $connection = 'mongodb';
protected $collection = 'products_1'; // this should be collection name and not the database name: products_1, products_2, etc.
...
}
CodePudding user response:
By default mongodb runs on port 27017, but looking at your connection string you are not sending that port to the connection. In case you are sure you are running mongodb in that port your connection string needs to be:
mongodb srv://marketplus_pr:[email protected]:57019?retryWrites=true&w=majority
On the other hand if you are not set the port at the moment of running your mongodb instance, this would be 27017, so the connection string will be:
mongodb srv://marketplus_pr:[email protected]:27017?retryWrites=true&w=majority