简体   繁体   English

如何从另一个文件引用Mongoose数据模型

[英]How to reference Mongoose data model from another file

How do you reference a Mongoose model in another file in a MEAN application? 您如何在MEAN应用程序的另一个文件中引用Mongoose模型? I am in login.js and need to reference user.js to findOrCreate a user. 我在login.js ,需要引用user.jsfindOrCreate创建用户。 Are my paths wrong or did I initialize the model incorrectly? 我的路径错误还是我对模型的初始化不正确? My error is undefined is not a function on the line to create a user. 我的错误是不确定的,不是在函数上创建用户。

File structure 档案结构

root
    models
        user.js
    passport
        login.js
    ...
        ...

login.js login.js

var User = require('./../models/user');
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;

module.exports = function(passport){

    // Google login
    passport.use(new GoogleStrategy({ 
        clientID: 'id',
        clientSecret: 'secret',
        callbackURL: 'http://127.0.0.1:3000/auth/google_oauth2/callback'
    }, function(accessToken, refreshToken, profile, done) {

        // Problem here? 
        User.findOrCreate({ googleId: profile.id }, function (err, user) {
            return done(err, user);
        });
    }));
};

user.js user.js

var mongoose = require('mongoose');

module.exports = mongoose.model('User', {

    googleId: {type: String, unique: true, required: true}
});

Change your user.js file: 更改您的user.js文件:

var mongoose = require('mongoose');

var Schema = mongoose.Schema;

module.exports = mongoose.model(
    'User', 
    new Schema({
         googleId: {type: String, unique: true, required: true}
    }
));

You might know more about Schema class. 您可能会了解有关Schema类的更多信息。

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

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