How does module.exports work

前端 未结 1 1690
误落风尘
误落风尘 2021-01-26 17:53

I\'m using Express and Mongodb to write my first web app and this is probably a noob question, but let\'s say I were to define a user model in a file called users.js and then ca

相关标签:
1条回答
  • 2021-01-26 18:09

    The standard way to define the model and using the schema in the controller

    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);
            });
        });
    
    0 讨论(0)
提交回复
热议问题