Gabriel Knies
Gabriel Knies

Reputation: 369

MongoDB/javascript/node.js/typescript : How to connect to two mongoose models?

I am creating an api, and i'm working with MongoDB as a dataBase, I've already created one model : in database.ts

import mongoose = require('mongoose');

const schema = new mongoose.Schema({
    id: String,
    username: String,
    gender: String,
    birthdate: String,
    password: String
});

export default mongoose.model('users', schema);

i'm connecting to the database using :

mongoose.connect('mongodb://localhost:27017/users', {useNewUrlParser: true});

in app.ts.

In utils.ts I imported the model like this :

import userDB from './database';

and for example, to retrieve all the users inside the database I use this (still in utils.js) :

  const users = await userDB.find();

Now my problem is that I want to have another model, which will have some keys insides, that I can retrieve and check if for example what the user has given to me correspond to one of the keys

I tried to search on most of the websites but didn't find the right answer.

I hope you can help me.

Thanks you in advance.

PS: it's my first post here, so if I did something wrong or my problem is not clear, feel free to tell me

Upvotes: 0

Views: 840

Answers (1)

Shivam
Shivam

Reputation: 3642

When you are connecting to Database you should connect to a project rather than to your schema like this

mongoose.connect('mongodb://localhost:27017/myProject', {useNewUrlParser: true});

You can replace myProject with whatever name you like. If the Project doesn't exist it will be created once you start your server and mongoDB is connected.

Then to retrieve all the users you can use this

import User from './user'; //Wherever your schema is

const Allusers = await User.find();

Now you can create as many Schema's you like and use it.

Upvotes: 1

Related Questions