我想用mongoose模型文件为用户保存用户的IP地址到mongoDB。有什么建议吗?我怎么做?
用户模块文件架构:
const userSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
trim: true,
minlength: 4
},
password: {
type: String,
required: true,
trim: true,
minlength: 4
},
IP: {
type: String
}
}, { timestamps: true });
使用express应该非常简单:
app.post('/your-route', async ( req, res ) => {
await YourModel.save({
IP: req.connection.remoteAddress,
// other fields
});
});
如果您在代理背后或者需要更复杂的方法,可以考虑使用类似https://www.npmjs.com/package/request-ip这样的库来确定IP地址。