skip to Main Content

I have the following schema:

const mongoose = require("mongoose");

const { ObjectId, Number } = mongoose.Schema.Types;

const CategoriesSchema = new mongoose.Schema(
  {
    name: {
        type: String,
        required: true,
    },
    img: {
        type: String,
        required: true,
    }
  }
);

mongoose.model("Categories", CategoriesSchema, 'categories');

My collection is called categories and it lives in the mxzconstruction database. I am doing a find on the Categories but it is not returning any data.

exports.getCategories = async (req, res) => {
console.log('GET CATEGORIES')

try {
    const categories = await Categories.find();
    console.log('categories', categories)
    res.status(200).json(categories)
} catch(error) {
    console.error(error);
    res.status(500).send('Problem getting categories.')
}

}

Supposed two databases, mxzconstruction and databaseXYZ, had a collection called ‘categories’, how would mongoose know which categories to return given that the database is not specified in mongoose model?

2

Answers


  1. You need to specify which database (databaseXYZ or mxzcondtruction) you want to connect to in your database connection string such as:

    mongodb://domain[:port]/<databaseName>
    

    For more information see Connection String URI Format

    Login or Signup to reply.
  2. Yes you need to specify database name in the connection Uri in .env file like

    mongoDbURI=mongodb://domain[:port]/<databaseName>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search