Gogu Gogugogu
Gogu Gogugogu

Reputation: 332

How to select one mongodb database among many in atlas with mongoose

Sorry if my question is a bit dumb, but I really can't figure out how to use mongoose. I have a sample database in atlas, which looks like this: sample database

I have the following code in js:

const uri ="myurl";
const mongoose = require("mongoose");
mongoose.connect(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function () {
  // here I dont know how to access one of the many databases and the collections inside the database
})

With mongodb it's clear, because MongoClient.connect returns a database object which gives access to any of the interested databases:

MongoClient.connect(url, function(err, db) {
  var sample_airbnb = db.db("sample_airbnb") // How can I access this in mongoose?
});

bellow is the full code:

const uri = "mongodb+srv://Alex:****@test0.ihhvy.mongodb.net/Test0?retryWrites=true&w=majority",
mongoose = require("mongoose"),
sc = new mongoose.Schema({
    name: String,
}),
model = mongoose.model("listingsAndReviews", sc);

mongoose.connect(uri, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  }, () => {
     model.find((err, x) => {
      if (err) throw err;
      console.log(x);
    });
})

Upvotes: 1

Views: 1418

Answers (2)

Mint
Mint

Reputation: 1059

Maybe this will work.

const mongoose = require('mongoose');
mongoose.connect(uri, {useNewUrlParser: true, useUnifiedTopology: true});
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function () {
  const VendorSchema= new mongoose.Schema({
    name: String,
    address: String
  });
  const Vendor = mongoose.model('Vendor', VendorSchema);
  const vendorOne = new Vender({ name: 'John Doe', address: 'Some Street, New York, NY' });
  vendorOne.save(function (err, vendor) {
    if (err) {
      console.log(err);
    } else {
      console.log('success');
    }
  });
})

Upvotes: 1

r_dmr
r_dmr

Reputation: 193

When connecting to mongodb via mongoose, if your mongodb uri doesn't contain any database name then it will connect to test database. So you have to define your database name at the end of the mongodb connection uri and it will connect to that defined database. Normally, the database connection uri has the structure like:

mongodb+srv://<username>:<password>@<cluster>/<your_desired_database>

so you should add your database name after a / at the end of the uri

Upvotes: 2

Related Questions