【问题标题】:MongoDB/javascript/node.js/typescript : How to connect to two mongoose models?MongoDB/javascript/node.js/typescript:如何连接到两个猫鼬模型?
【发布时间】:2020-12-09 21:33:43
【问题描述】:

我正在创建一个 api,我正在使用 MongoDB 作为数据库, 我已经创建了一个模型: 在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);

我正在使用 :

连接到数据库
mongoose.connect('mongodb://localhost:27017/users', {useNewUrlParser: true});

在 app.ts 中。

在 utils.ts 我这样导入模型:

import userDB from './database';

例如,要检索数据库中的所有用户,我使用它(仍在 utils.js 中):

  const users = await userDB.find();

现在我的问题是我想要另一个模型,它内部有一些键,我可以检索并检查例如用户给我的内容是否对应于其中一个键

我尝试在大多数网站上搜索,但没有找到正确的答案。

我希望你能帮助我。

提前谢谢你。

PS:这是我在这里的第一篇文章,所以如果我做错了什么或我的问题不清楚,请随时告诉我

【问题讨论】:

    标签: javascript node.js mongodb typescript mongoose


    【解决方案1】:

    当你连接到数据库时,你应该连接到一个项目,而不是像这样连接到你的schema

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

    您可以将myProject 替换为您喜欢的任何名称。如果项目不存在,它将在您启动服务器并连接 mongoDB 后创建。

    然后检索所有可以使用的用户

    import User from './user'; //Wherever your schema is
    
    const Allusers = await User.find();
    

    现在您可以创建任意数量的Schema's 并使用它。

    【讨论】:

      猜你喜欢
      • 2020-11-02
      • 2014-12-28
      • 2020-02-14
      • 2016-04-29
      • 1970-01-01
      • 2013-12-03
      • 1970-01-01
      • 2021-01-01
      相关资源
      最近更新 更多