我尝试创建一个专用的mongoose 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);

答案 0 :(得分:0)
您的代码存在许多问题,首先要了解模块在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);
然后需要导入profileSchema,它位于profile中,取决于你的文件路径。
const profileSchema = require('./model/profile.js');
答案 1 :(得分:0)
你要做的是
// 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');