【发布时间】: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