【问题标题】:Cannot save data in mongoDb collection : "ReferenceError: Model is not defined"无法在 mongoDb 集合中保存数据:“ReferenceError:模型未定义”
【发布时间】:2020-07-04 22:24:13
【问题描述】:

我正在尝试将模型保存到 mongoDb 集合,但不断收到此“ReferenceError: Model is not defined”

模型文件中的代码如下所示:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;
const MetainfoSchema = new Schema({


  portfolio: {
    title: String,
    subTitle: String,
  },
  cv: {
    title: String,
    subTitle: String,
  },
  contact: {
    title: String,
    subTitle: String,
  }



}, { collection: "metainfo" });

const Metainfo = mongoose.model('Metainfo', MetainfoSchema);

const mModel = new Metainfo({

  portfolio: {
    title: "Portfolio",
    subTitle: "Checkout my works",
  },
  cv: {
    title: "Download my cv",
    subTitle: "Aviable in three languages",
  },
  contact: {
    title: "Let's talk",
    subTitle: "Send me an e-mail"
  }



});
mModel.save(function (err, doc) {
  if (err) return console.error(err);
  console.log("Document inserted succussfully!");
});

module.exports = Metainfo;

当尝试保存模型时,它显示为未定义,但我确实使用 mongoose.model 来定义它,我一直在尝试找到修复但没有成功。

错误:

[server] ReferenceError: Model is not defined
[server]     at Object.<anonymous> (C:\Users\andpa\Desktop\files\Projects\REACT\portfolio2020\server.js:32:16)
[server]     at Module._compile (internal/modules/cjs/loader.js:1138:30)
[server]     at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
[server]     at Module.load (internal/modules/cjs/loader.js:986:32)
[server]     at Function.Module._load (internal/modules/cjs/loader.js:879:14)
[server]     at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
[server]     at internal/main/run_main_module.js:17:47

请帮忙

Server.js:

const express = require("express");
const morgan = require("morgan");
const path = require("path");
const mongoose = require("mongoose");
const app = express();
const PORT = process.env.PORT || 8080;

const routes = require("./routes/api");

mongoose.connect("mongodb://localhost/portfolioDB", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

mongoose.connection.on("connected", () => {
  console.log("Mongoose is connected");
});

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

if (process.env.NODE_ENV === "production") {
  app.use(express.static("client/build"));
}

app.use(morgan("tiny"));
app.use("/api", routes);

app.listen(PORT, console.log(`Server is runing at ${PORT}`));

【问题讨论】:

  • 分享您的server.js 文件。似乎某些导入导致错误。
  • @SujeetAgrahari 添加了代码。

标签: node.js reactjs mongodb express


【解决方案1】:

在创建新的元信息

之前,您需要创建一个如下所示的新模型
mongoose.model('Metainfo', MetainfoSchema);
const Metainfo = mongoose.model('Metainfo');

之后你可以创建一个模型

const mModel = new Metainfo({
  portfolio: {
    title: "Portfolio",
    subTitle: "Checkout my works",
  },
  cv: {
    title: "Download my cv",
    subTitle: "Aviable in three languages",
  },
  contact: {
    title: "Let's talk",
    subTitle: "Send me an e-mail"
  }
});

【讨论】:

    【解决方案2】:

    你必须这样写模型。

    const mongoose = require('mongoose'),
        autoIncrement = require('mongoose-sequence')(mongoose);
    const BreakReasonSchema = require('../models/BreakReason');
    
    const UserInfoSchema = new mongoose.Schema({
        id: {
            type: Number
        },
        company_name_id: {
            type: Number
        },
        country_name_id: {
            type: Number
        },
        user_type_id: {
            type: Number
        },
        user_email: {
            type: String
        },
        user_pass: {
            type: String
        },
        first_name: {
            type: String
        },
        last_name: {
            type: String
        },
        user_mobile: {
            type: String
        },
        account_owner: {
            type: Boolean
        },
        account_owner: {
            type: Boolean
        },
        added_date: {
            type: Date
        },
        update_date: {
            type: Date
        },
        delete_date: {
            type: Date
        },
        delete_status: {
            type: Boolean
        },
        user_social_uid: {
            type: String
        },
        status: {
            type: Boolean
        }
    
    }, {timestamps: true});
    UserInfoSchema.virtual('break_reason_info', {
        ref: BreakReasonSchema,
        localField: 'company_name_id',
        foreignField: 'company_name_id'
    });
    UserInfoSchema.virtual('social_account_info', {
        ref: 'businessapp_companysocialaccountinfo',
        localField: 'company_name_id',
        foreignField: 'company_name_id'
    });
    UserInfoSchema.virtual('business_setup_info',{
        ref: 'businessapp_businesssetup',
        localField: 'company_name_id',
        foreignField: 'company_name_id',
        justOne:true
    });
    UserInfoSchema.set('toObject', {virtuals: true});
    UserInfoSchema.set('toJSON', {virtuals: true});
    //UserInfoSchema.plugin(autoIncrement, {id: "UserInfo", inc_field: 'id'});
    module.exports = mongoose.model("businessapp_userinfo", UserInfoSchema, 'businessapp_userinfo');
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-12
      相关资源
      最近更新 更多