我有两个利用 mongo 集合查询的 meteor 函数。
UI.registerHelper('studentsInCourse', function() {
var courseID = Router.current().params.courseID;
let userIdArray = Enrollment.find(
{ CourseID: courseID}
).map((e) => { return e.UserID});
console.log(userIdArray); //this array correctly has multiple objs in it
var userArray = Meteor.users.find(
{ _id: { $in: userIdArray }}).map((c) => { return c });
console.log(userArray);
return userArray;
}),
Template.registerHelper('course_list', function(){
let courseIdArray = Enrollment.find(
{ UserID: Meteor.userId(), EducatorFlag: false },
{ fields: { CourseID: 1 }}).map((e) => { return e.CourseID });
return Courses.find(
{ _id: { $in: courseIdArray }}).map((c) => { return c });
})
course_list 函数正常工作并从 Courses 集合中返回 Course 对象的列表。然而,当我记录 userIdArray 时,studentsInCourse 函数会正确打印出一个数组,但它只将一个用户对象放入 userArray 中。这恰好对应于 userIdArray 中最后一个对象的 _id。这些函数对我来说看起来相同,但我不明白为什么它们返回的结果不同。
最佳答案
取自 Meteor.users Meteor API 文档部分:
Like all Mongo.Collections, you can access all documents on the server, but only those specifically published by the server are available on the client.
如果您已登录并从客户端调用以下内容
Meteor.users.find({
_id: {
$in: userIdArray
}
}).map((c) => { return c });
然后默认情况下Meteor.users.find()
只会返回您登录的用户详细信息(这是一项安全功能 - 您不希望人们能够获取所有用户的列表)您的用户)。所以你的光标最多会指向一个用户。如果您登录的用户 _id
位于 userIdArray
中,那么您将仅对该用户运行关联的 map
函数,这就是为什么您仅返回一个用户对象。
如果您想对客户端的所有用户运行此操作,那么您需要考虑设置自己的订阅/发布,以将您想要的用户数据发送到客户端(或考虑利用 Meteor 方法来实现类似的目标 - 您可以创建一个方法来查找并返回所有匹配的用户)。
关于javascript - Meteor Mongo $in 与数组仅返回最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38732379/