piggyback
piggyback

Reputation: 9254

DB-ref in mongoose without Schema.ObjectId?

in my code people can follow other people. So far everything is ok apart from this fact: in the userScheme I have this field.

, following: [{ type: Schema.ObjectId, ref: 'Users' }]

Since every user has an username, it's more versatile for me to use dbref with the username. is there a way to do something like this?

, following: [{ type: Users.username, ref: 'Users' }]

Many thanks, g

Upvotes: 5

Views: 2804

Answers (3)

dhruvin vaghasiya
dhruvin vaghasiya

Reputation: 144

mongoose's populate function is mongodb's lookup in the abstract but populate only creates refs to object id but if you are sure then you will have a unique username for every user and then if you want to populate data using username then you can use lookup and result will be the same.

Upvotes: 0

irok
irok

Reputation: 96

You can only reference via ObjectId to a collection like your first code snippet.

[{ type: Schema.ObjectId, ref: 'Users' }]

When making a query with populate(), you can specify the fields you want to return. In your case, it woud look something like

User.find({}).populate('following', 'username').exec(function(err,doc) {});

Each object in the following array would look like

{ _id: 'xxxxxxxxxx', username: 'xxxxxxxx' }

Upvotes: 3

JohnnyHK
JohnnyHK

Reputation: 311865

No, only ObjectId values that refer to the _id property of another collection can be used as refs.

Confirmed in the source code.

Upvotes: 4

Related Questions