1

I want to save users IP address to mongoDB using mongoose model file for user. Any has any suggestions how can I do that?

Users module file schema:


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 });

1 Answers1

2

Using express this should be fairly simple:

app.post('/your-route', async ( req, res ) => {
  await YourModel.save({ 
         IP: req.connection.remoteAddress, 
         // other fields
        });
});

If you're behind a proxy or need a more sophisticated approach you can consider using a library like https://www.npmjs.com/package/request-ip to determine the IP-address.

eol
  • 15,597
  • 4
  • 25
  • 43
  • when I run it, I get " IP:"::1" in DB, as far as I understand it means 127.0.0.1, right? Will it work properly ( will I get proper local IP? ) when I run it on other network? – Elvinas Kujelis Nov 29 '20 at 15:49
  • 1
    Yes, since you're using IPv6 you'll see ::1 if you perform the request from your localhost. – eol Nov 29 '20 at 16:01