mongodb Mongoose中的DB-ref没有架构,ObjectId?

rbl8hiat  于 2023-01-30  发布在  Go
关注(0)|答案(3)|浏览(167)

在我的代码中,人们可以跟随其他人。2到目前为止,除了这个事实之外,一切都很好:在userScheme中我有这个字段。

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

因为每个用户都有一个用户名,所以我使用dbref和用户名会更灵活。有没有办法做到这一点?

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

非常感谢g

envsm3lx

envsm3lx1#

不可以,只有引用另一个集合的_id属性的ObjectId值才能用作引用。
source code中确认。

1sbrub3j

1sbrub3j2#

只能通过ObjectId引用第一个代码段之类的集合。

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

当使用populate()进行查询时,可以指定要返回的字段。

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

以下数组中的每个对象将类似于

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

jyztefdp3#

mongoose的populate函数是mongodb的抽象查找,但populate只创建对对象id的引用,但如果你确定,那么你将为每个用户拥有一个唯一的用户名,然后如果你想使用用户名填充数据,那么你可以使用lookup,结果将是相同的。

相关问题