>我有一个包含 2 个文档的 MongoDB -User
和Clinic
。
用户文档包含与应用程序用户(即用户帐户)相关的数据。
Clinic 文档包含与诊所相关的信息,其中包括提供者列表,其中提供者是对User
模型的引用。
这些模型的架构如下所示。
用户模型.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
module.exports = User= mongoose.model('users', UserSchema);
诊所模型.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ClinicSchema = new Schema({
providers: [
{
user: {
type: Schema.Types.ObjectId,
ref: 'users'
}
}
],
name: {
type: String,
required: true
}
});
module.exports = Clinic = mongoose.model('clinics', ClinicSchema);
在前端,我有用户"个人资料",他们可以在其中查看他们的信息。为了填充此视图,我在后端有一个 GET 路由,用于提供用户的数据(注意:他们必须登录才能访问)。
在从后端发送数据之前,我想找到用户是提供者的诊所(即它们在provider
数组中的诊所对象),并将其添加到 JSON 响应中。将数据添加到 JSON res 很容易,但我正在努力弄清楚如何查看Clinic
条目并返回req.user.id is === provider.user.toString()
当前路线
router.get(
'/profile',
passport.authenticate('jwt', { session: false }),
(req, res) => {
User
.findById(req.user.id)
.then(user => {
Clinic
.find()
.then(clinics => {
userClinic = clinics.filter(clinic => {
clinic.providers.filter(provider => {
provider.user.toString === req.user.id;
});
});
console.log(userClinic);
});
})
.catch(err => res.status(404).json({notFound: 'User not found'}));
}
);
在上面的代码中,console.log(userClinic)
返回一个空数组。
我怎样才能让这条路由console.log(userClinic)
,以便userClinic
是用户在诊所providers[]
的Clinic
对象的数组?
注意:console.log() 稍后将替换为将数组附加到作为 JSON 返回的对象中的逻辑。
我会说你的filter
无法正常工作,并且有几个问题:
- 你的过滤函数不会
return
一个值被filter
评估为真值或假值:所以,隐式地,这些函数总是return undefined
,这是假的,这导致没有元素被filter
验证(即空数组) - 你测试
provider.user.toString === req.user.id;
而你可能的意思是provider.user.toString() === req.user.id
(顺便说一下,provider.user
肯定已经是一个字符串) - 您并没有真正为
clinics.filter
使用的函数提供过滤测试(独立于缺少的return
),我想它会像return clinic.providers.filter(...).length > 0
- 或者您可以使用更适合此目的的find
最后,你会得到这样的东西:
// don't forget to *declare* the variable with var/let/const!
let userClinics = clinics.filter(clinic => {
return clinic.providers.find(provider => {
return provider.user === req.user.id;
});
});
但是,这项工作可以更容易地完成。您可以使用MongoDB为您对数据进行排序,而不是检索整个集合。这应该有效:
route.get(... => {
const promiseUser = User.findById(req.user.id);
const promiseClinics = Clinic.find({
"providers.user": req.user.id
});
Promise.all([promiseUser, promiseClinics]).then(results => {
let user = results[0];
let clinics = results[1];
// do stuff with these profile data
});
});