Node.js module.exports是如何工作的
我正在使用Express和Mongodb编写我的第一个web应用程序,这可能是一个noob问题,但假设我要在一个名为users.js的文件中定义一个用户模型,然后在文件中的某个地方调用Node.js module.exports是如何工作的,node.js,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])导入应用程序中的其他文件后,为什么我可以调用新用户并访问模型,而不必调用新用户。User?定义模
const user=module.exports=mongoose.model('user',UserSchema)
将users.js(通过
const User=require([path to users.js])
导入应用程序中的其他文件后,为什么我可以调用新用户
并访问模型,而不必调用新用户。User
?定义模型和在控制器中使用模式的标准方法
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);
});
});
这实际上是一个非常好的模型,如果你有一个链接来说明它的来源,这样我就可以查看每个字段的分类,那太棒了。但是我仍然有一个问题,为什么用户模型可以在整个应用程序中访问,而不必调用
[modulename].[model]
这是一个我正在研究的实时项目模型,由我创建。您可以按照mongoose、nodejs文档创建Wonder。您的问题答案就是模块。导出将使您导入用户模型并在整个应用程序中访问,而无需callWelcome,如果您觉得这是一个好的答案,那么您可以向上投票并访问使其正确,这将节省许多具有相同查询的开发人员的时间