【问题标题】:Mongoose multiple models for same connectionMongoose 用于同一连接的多个模型
【发布时间】:2020-12-07 22:24:52
【问题描述】:

我想使用带有单个 mongoose.connect() 的模型。

我在 MongoDB 中有这样的简单数据库

ProjectDB
|_ tableA
|_ tableB

我在 NodeJs 中有简单的服务器

ProjectFolder
|-> server.js
|-> /db
    |-> mongooseDb.js
    |-> /models
       |-> tableA.js
       |-> tableB.js

mongooseDb.js 连接数据库并创建单个实例

const mongoose = require('mongoose');
function Connect(){
    return new Promise((resolve,reject)=>{
        mongoose.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true})
        .then((res)=>{
            global.mongoose=mongoose;
            resolve("Connection Successfull");
        })
        .catch((e)=>{reject(e);})
    })
}
module.exports={
    Connect
}

server.js 创建服务器并监听端口

var express = require("express");
var db=require("./db/mongooseDb");
var tableA=require("./db/models/tableA");
const app = express();
db.Connect()
.then((res)=>{
    app.listen(port, () => console.log("Server Ready On port " + port));
    tableA.Save({ name: 'John' });
})
.catch((err)=>{})

tableA.js tableA 的模型

class tableA{
  constructor(){
    this.tableModel=global.mongoose.model('tableA', { name: String });
  } 
  Save(data){
    this.tableModel.create(data)
    .then((res)=>{console.log(res)})
    .catch((err)=>{console.log(err)})
  }
}  
const _tableA = new tableA();
module.exports={
  _tableA
}

当我运行代码时出现错误。

this.tableModel=global.mongoose.model('tableA', { name: String });
TypeError:无法读取未定义的属性“模型”

  • 是否必须为每个模型创建单独的连接对象?
  • 我可以为多个模型共享同一个连接对象吗? (表A,表B)
  • 如果模型共享相同的连接对象,是否会导致它们的使用出现问题?

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    在调试和更多研究之后,我注意到 require("mongoose") 返回相同的对象实例。所以我把代码改成这样。

    tableA.js

    const mongoose = require('mongoose');
    class tableA{
      constructor(){
        this.tableModel=mongoose.model('tableA', { name: String });
      } 
      Save(data){
        this.tableModel.create(data)
        .then((res)=>{console.log(res)})
        .catch((err)=>{console.log(err)})
      }
    }  
    const _tableA = new tableA();
    module.exports={
      _tableA
    }
    

    【讨论】:

      猜你喜欢
      • 2018-10-22
      • 2019-09-13
      • 1970-01-01
      • 2018-07-10
      • 2014-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-02
      相关资源
      最近更新 更多