module.exports如何工作

时间:2018-04-22 15:09:49

标签: node.js

我使用Express和Mongodb编写我的第一个Web应用程序,这可能是一个noob问题,但是我要说我要在一个名为users.js的文件中定义用户模型,然后调用const User = module.exports = mongoose.model('User', UserSchema)文件中的某个地方。

将users.js(通过const User = require([path to users.js]))导入应用中的其他文件后,为什么我可以拨打new User并访问该模型,而不必拨打new users.User

1 个答案:

答案 0 :(得分:0)

定义模型和在控制器中使用模式的标准方法

user.js的

 //User Model
var mongoose = require('mongoose');

var userSchema = new mongoose.Schema({
  id: String,
  name: {
    type: String,
    index: true
  },
  email: {
    type: String,
    trim: true,
    index: true,
    lowercase: true,
    unique: true
  },
  mobile: {
    type: String,
    trim: true,
    index: true,
    unique: true,
    required: true
  },
  profilePic: String,
  password: { type: String },
  locations: [{}],
  location: {
    type: { type: String, default: 'Point', enum: ['Point'] },
    coordinates: { type: [], default: [0, 0] },
    name: String,
    shortAddress: String
  },
  address: String,
  gender: String,
  dob: Date,
  signupType: { type: String, enum: ['facebook', 'google'] },
  deviceType: String,
  createdTime: Date,
  updatedTime: Date,
  googleToken: String,
  facebookToken: String,
  fcmToken: String,
  facebookLink: String,
  facebookId: String,
  memberType: String,
  deviceId: String,
  preferences: [{}],
  loginData: [{}],
  token:String,
  isVerified: Boolean,
  isMobileVerified: Boolean,
  isEmailVerified: Boolean,
  lastSeen: Date
});

// 2D sphere index for user location

userSchema.index({ location: '2dsphere' });

mongoose.model('User', userSchema);

module.exports = mongoose.model('User');

UserController.js

//User Controller 
var User = require('./User');


    // RETURNS ALL THE USERS IN THE DATABASE
    router.get('/', function (req, res) {
        User.find({}, function (err, users) {
            if (err) return res.status(500).send({ errors: "There was a problem finding the users." });
            res.status(200).send(users);
        });
    });