codebreaker
codebreaker

Reputation: 35

mongoose object relationship

I am trying to create a new access token object. In the debugger, I can see that the user._id value is returned correctly. But when assigned to the token user field, the value of token.user._id is undefined and token.user.id is some garbage value. The same behaviour is observed even after saving the token.

exports.create = function(user, client, deviceId, done) {
    if (!user) return done(new Error('Failed to create client without user'));
    var token = new AccessToken({
        user: user._id,
        client: client._id,
        deviceId: deviceId
    });
    token.save(function(err) {
        if (err) return done(err);
        return done(null, token);
    });
};

Upvotes: 2

Views: 103

Answers (2)

Rox
Rox

Reputation: 811

With

var token = new AccessToken({
    user: user._id,
    client: client._id,
    deviceId: deviceId
});

You're assigning your user's id to user so you can use it with token.user. If you want to access your user's id with token.user._id you should do :

var token = new AccessToken({
    user: user,
    client: client._id,
    deviceId: deviceId
});

but you will have to use .populate('user') when querying to access to token.user._id

Upvotes: 3

Jack Guy
Jack Guy

Reputation: 8523

In mongoose you use .id to access the ._id field as a string. What is the difference between id and _id in mongoose?

Upvotes: 0

Related Questions