简体   繁体   English

MongoDB/javascript/node.js/typescript:如何连接到两个 mongoose 模型?

[英]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我正在创建一个 api,我正在使用 MongoDB 作为数据库,我已经创建了一个 model:在 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:在 utils.ts 中,我像这样导入了 model:

import userDB from './database';

and for example, to retrieve all the users inside the database I use this (still in utils.js):例如,要检索数据库中的所有用户,我使用它(仍在 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现在我的问题是我想要另一个 model,它里面有一些钥匙,我可以检索并检查例如用户给我的东西是否对应于其中一个钥匙

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 PS:这是我在这里的第一篇文章,所以如果我做错了什么或者我的问题不清楚,请随时告诉我

When you are connecting to Database you should connect to a project rather than to your schema like this当您连接到数据库时,您应该连接到一个项目而不是像这样连接到您的schema

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

You can replace myProject with whatever name you like.您可以将myProject替换为您喜欢的任何名称。 If the Project doesn't exist it will be created once you start your server and mongoDB is connected.如果该项目不存在,它将在您启动服务器并连接 mongoDB 后创建。

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.现在您可以创建任意数量的Schema's并使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM