[英]Why is the Express (Node.js) request object read-only?
I'm using PassportJS but would like to have the user ID ( _id
) available to the front-end client. 我正在使用PassportJS,但想让前端客户端可以使用用户ID(
_id
)。 So I'm trying to splice in _id
into the req.user.userInfo
object: 所以我试图将
_id
拼接到req.user.userInfo
对象中:
/** 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. 但是,
_id
在返回的JSON中不存在。 Can objects be read-only? 对象可以是只读的吗?
Update: output of console.log
: 更新:
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. 好的,
req.user
理论:虽然req
是普通的javascript对象, req.user
是req.user
模型实例。 Mongoose has a few magical features, namely virtual properties and transforms during toObject
and toJSON
. 猫鼬具有一些神奇的功能,即虚拟属性和
toObject
和toJSON
期间的toObject
。 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. 我怀疑
req.user.userInfo
可能是猫鼬虚拟的,这就是为什么对它的修改会被忽略的原因,因为每次访问req.user.userInfo
猫鼬都会重新生成值。
If that is true (my evidence is the __v
property indicating mongoose, you can solve it by doing this: 如果是这样(我的证据是表示猫鼬的
__v
属性,您可以通过执行以下操作解决问题:
// 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. 对于更大的问题,
req
对象不是只读的。 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. 另外:
_id
是有效的标识符,因此您应该只使用普通的点语法,但方括号语法是等效的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.