mongoose - 填充不工作,不填充代码工作
问题描述
我在填充模式的字段时遇到问题,我尝试了很多次,但我无法弄清楚问题:FUNCTION:
function xyz (req, res) {
User.findOne({_id: req.payload._id })
.populate("ABC.xyzID")
.exec((err, user) => {
if (err) {
return res.json ({'success': false, 'message': 'Could not retrieve ABC.'});
}
console.log(user);
return res.json ({'success': true, 'message': 'ABC fetched successfully', user });
});
}
架构:
const UserSchema = new mongoose.Schema({
name:{
type: String,
required: true,
trim: true
},
ABC:{
xyzID:{
type: mongoose.Schema.Types.ObjectId,
ref: 'xyz'
},
},
LMN:{
yyyID:[{
type: mongoose.Schema.Types.ObjectId,
ref: 'yyy'
}],
EmployeeID:[{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}]
}
});
在这里我可以通过填充它来访问:LMN.yyyID,但它不适用于 ABC.xyzID,没有填充我可以看到 xyzID,但它的 _id 格式。所以基本上它只是填充不起作用
解决方案
请看这个 Schema 设计。这是用户。
// user.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create schema
const UserSchema = new Schema({
username: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
module.exports = User = mongoose.model('user', UserSchema);
现在这里是活动模式。现在你可以看到我从“用户”架构中引用 userId。因此,您需要确保您的集合名称和参考名称相同。在此之后,它应该工作。
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create schema
const ActivitySchema = new Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user'
},
text: {
type: String,
required: true
}
});
module.exports = Activity = mongoose.model('activity', ActivitySchema);
然后尝试查询
Activity.findOne({_id: req.payload._id })
.populate('userId')
.then(result => { console.log(result); })
.catch(err => { console.log(err); });
您将在 userId 对象中看到用户信息。
推荐阅读
- azure-application-insights - Azure App Insights 操作计数异常高
- android - 如何检查 android 应用 (Zoom) 过去是否使用过相机?
- php - 在视觉作曲家中发布后未显示图标和图像
- ios - 如何在所有内容之上呈现视图控制器?
- mongodb - 无法使用 Mongoose 删除数组中的对象
- qt - 如何使用 OpenSSL 部署 QT 应用程序
- python-3.x - 如何将模拟变量与 Qt Lcd 编号链接
- reactjs - 大于有条件的反应不起作用
- javascript - 如何将文本芯片附加到 vuetify 中的文本字段
- python - 隐藏情节表达动画中的播放和停止按钮