DB-ref在没有Schema.ObjectId的mongoose?
在我的代码中,人们可以跟随其他人。 到目前为止,除了这个事实之外,一切都还好:在userScheme中我有这个字段。
, following: [{ type: Schema.ObjectId, ref: 'Users' }]
由于每个用户都有一个用户名,所以我使用dbref的用户名更加通用。 有没有办法做这样的事情?
, following: [{ type: Users.username, ref: 'Users' }]
非常感谢,g
不,只有引用另一个集合的_id
属性的ObjectId
值可以用作参考。
在源代码中确认。
你只能通过ObjectId引用像你的第一个代码片段的集合。
[{ type: Schema.ObjectId, ref: 'Users' }]
使用populate()进行查询时,可以指定要返回的字段。 在你的情况下,它会看起来像
User.find({}).populate('following', 'username').exec(function(err,doc) {});
以下数组中的每个对象都是这样的
{ _id: 'xxxxxxxxxx', username: 'xxxxxxxx' }