通过 npm 包共享猫鼬模型

问题描述

我正在编写一些使用相同数据库和架构的应用程序。 我需要在所有应用程序之间共享猫鼬模型 - 每个应用程序都有自己的快速服务器。

我尝试创建一个模型服务器并使用 mongoose-gen npm 请求 JSON,它工作但不完全,所以我必须寻找另一个解决方案。

在这里找到了一些关于为此创建 npm 包的答案,我这样做了,但仍然缺少一些东西 - 我发布了包并将其导入到我的代码中,但是当我实际尝试查询架构时 - 什么也没发生,服务器返回 500 并报错:

MongooseError:操作 examples.insertOne() 缓冲在 10000 毫秒后超时。

我认为我的包裹中缺少某些东西,但我不知道是什么。

这是包中包含的内容

./index.js

    const example =require("./SystemWave")
    
    module.exports.Example=example

./SystemWave.js

    const mongoose = require('mongoose')

    const systenWaveSchema = mongoose.Schema({
        timestamp: { type: Date,default: Date.Now },subject: {type:String,require: true},})
    
    module.exports = mongoose.model('example',systenWaveSchema)

./package.json

    {
      "name": "modelsnpm","version": "1.0.6","description": "","main": "index.js","scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },"author": "","license": "ISC","dependencies": {
        "mongoose": "^5.11.15"
      }
    }
./node_modules

./package-lock.json

./README.md

我不知道是否应该添加数据库 URL 或其他任何内容

更新

在这里找到了另一个解决方案:

Schemas in external module not working in Node.js

但它似乎返回相同的错误...

解决方法

最终,我想出了这个解决方案:

Schemas in external module not working in Node.js

对代码进行了一些更改,它起作用了!

我所做的更改:

const user=require('./models/user');
   
 used in the schema file
    this.models = {
        user: user
    }

希望对你们有帮助:)