简体   繁体   English

出口猫鼬模型

[英]Exporting mongoose model

I am trying to export the mongoose variable to another JS file but I can't get it to work. 我试图将mongoose变量导出到另一个JS文件,但无法正常工作。

I want to export the user variable which is a mongoose model. 我想导出用户变量,它是猫鼬模型。 If I include the mongoose things directly inte results.js then it will work. 如果我将猫鼬的东西直接包含在results.js中,那么它将起作用。

Error: TypeError: app.user is not a constructor at projects\\api\\js\\results.js:12:23 错误:TypeError:app.user不是projects \\ api \\ js \\ results.js中的构造函数:12:23

app.js app.js

var express = require("express");
var session = module.exports = require('express-session');
var bodyParser = module.exports = require('body-parser');

//MongoDB
var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/time_report");

var userSchema = new mongoose.Schema({
    name: String,
    password: String
});

var user = mongoose.model("user", userSchema);

var app = module.exports = express();
exports.user = user; //This variable is not reachable

results.js results.js

var app = require("./app.js");

function showDate() {
    app.get("/results", function(req, res) {
        //Get login info
        var uName = req.query.username;
        var pw = req.query.password;

        var newUser = app.user({ //Fail here
            name: uName,
            password: pw
        });

        console.log(newUser.name);

        // Check to match with database
        user.findOne({ name: newUser.name, password: newUser.password }, function(err, user) {
            if (err) return handleError(err);

            if (user) {
                console.log("Logged in");
                //console.log('This is great! %s %s', user.name, user.password);
                res.render("results", { data: newUser });
            } else {
                res.send("Failed to login");
            }

        });
    });
}

In app.js , change this: app.js ,更改以下内容:

//...        
var app = module.exports = express();
exports.user = user; //This variable is not reachable

with this: 有了这个:

//...        
module.exports = {
    app: express(),
    user
}

Then, in result.js change this line: 然后,在result.js更改以下行:

var app = require("./app.js"); // <----- NO

with this other one: 与另外一个:

var {app, user} = require("./app.js"); // <----- YES

And of course, in result.js you want instantiate a new user (so don't forget the new keyword): 当然,在result.js中,您想实例化一个新用户 (因此请不要忘记new关键字):

var newUser = new user ({ //No longer fails here
    name: uName,
    password: pw
});

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

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