繁体   English   中英

找不到猫鼬模式

[英]Can 't find mongoose schema

我尝试创建一个专用的猫鼬createConnection。 Node.js融为一体:

MyModel = conn.model('Profile', profileSchema), 

profileSchema is not defined.

但是我哪里出错了?

 //my db.js const mongoose = require('mongoose'); const conn = mongoose.createConnection = ("mongodb://localhost:27017/myDatabase"), MyModel = conn.model('Profile', profileSchema), m = new MyModel; m.save(); //works; if (process.env.NODE_ENV === 'production') { conn = process.env.MONGODB_URI; } require('./profiles) 

这是我的模型页面的其余部分:

 // my profile.js // JavaScript source code const mongoose = require('mongoose'); const profileSchema = new mongoose.Schema({ firstName: { type: String, required: true }, lastName: { type: String, required: true }, }); var MyModel = mongoose.model('Profile', profileSchema); 

您的代码有很多问题,首先了解模块在javascript中的工作方式。 您需要导出profileSchema以便在app.js中使用,应该是,

const mongoose = require('mongoose');
const profileSchema = new mongoose.Schema({
    firstName: {
        type: String,
        required: true
    },
    lastName: {
        type: String,
        required: true
    },


    });
module.exports = mongoose.model('Profile', profileSchema);

然后需要导入profileProfile中的profileSchema,具体取决于您的文件路径。

const profileSchema = require('./model/profile.js');

你要做的是

// my profile.js

// JavaScript source code
const mongoose = require('mongoose');


const profileSchema = new mongoose.Schema({
    firstName: {
        type: String,
        required: true
    },
    lastName: {
        type: String,
        required: true
    },


    });

module.exports = mongoose.model('Profile', profileSchema);

并在您的app.js文件中像这样放置

const profileInfo= require('./../model/profile.js');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM