Вопрос

I'm using PassportJS but would like to have the user ID (_id) available to the front-end client. So I'm trying to splice in _id into the req.user.userInfo object:

/** Create user */
exports.create = function (req, res, next) {
    var newUser = new User(req.body);
    newUser.provider = 'local';

    newUser.save(function(err) {
        if (err) {
            // Manually provide our own message for 'unique' validation errors, can't do it from schema
            if(err.errors.email.type === 'Value is not unique.') {
                err.errors.email.type = 'The specified email address is already in use.';
            }
            return res.json(400, err);
        }
        // Login after registration
        req.logIn(newUser, function(err) {
            if (err) return next(err);

            // Splice in _id
            req.user.userInfo['_id'] = req.user['_id'];
            console.log('newUser', req.user, req.user.userInfo);

            return res.json(req.user.userInfo);
        });
    });
};

However, the _id is not present in the returning JSON. Can objects be read-only?


Update: output of console.log:

newUser { __v: 0,
  name: 'tom@myemail.com',
  hashedPassword: '$2a$10$r9ZL1JerqDko8zw72q5J5ONYZAWDpHDF1ROt0k35/1fRgfqNedGWG',
  salt: '$2a$10$r9ZL1JerqDko8zw72q5J5O',
  provider: 'local',
  email: 'tom@myemail.com',
  _id: 534552e8ecb0d69648000003,
  role: 'user' } { name: 'tom@myemail.com', role: 'user', provider: 'local' }
Это было полезно?

Решение

OK, 2nd theory: While req is a normal javascript object, req.user is a mongoose.js model instance. Mongoose has a few magical features, namely virtual properties and transforms during toObject and toJSON. I suspect maybe req.user.userInfo is a mongoose virtual, which is why modifications to it get ignored because mongoose regenerates the value every time req.user.userInfo is accessed.

If that is true (my evidence is the __v property indicating mongoose, you can solve it by doing this:

        // Splice in _id
        var userInfo = req.user.userInfo;
        userInfo._id = req.user._id;
        console.log('newUser', req.user, userInfo);

        return res.json(userInfo);

And to your larger question, the req object is not read-only. There's some simpler bug going on in your code.

Aside: _id is a valid identifier so you should just use normal dot syntax, but square bracket syntax is equivalent.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top