node.js - 为什么secondaryUser字段会影响findOne的工作?
问题描述
在这我使用 nodejs 与 express 和 mongoose。我的问题是更改 secondaryUser 字段如何影响 findOne 是否有效?如果我将它作为friends.id,它可以工作并且它会找到正确的个人资料,但我想将它与个人资料中的用户字段联系起来。如果我将其更改为friends.user.id,findOne 将失败并在catch 中发送404 错误。
router.post(
"/:handle",
passport.authenticate("jwt", {
session: false
}),
(req, res) => {
Profile.findOne({ handle: req.params.handle }).then(friends => {
const newFriend = new Friend({
initialAccepted: true,
initialUser: req.user.id,
secondaryUser: friends.id
});
newFriend
.save()
.then(Friend => res.json(Friend))
.catch(err =>
res.status(404).json({
friendnotfound: "No people found with that handle"
})
);
});
}
);
用于朋友的模式是
const FriendSchema = new Schema({
initialUser: {
type: Schema.Types.ObjectId,
ref: "profile"
},
secondaryUser: {
type: Schema.Types.ObjectId,
ref: "profile"
},
initialAccepted: {
type: Boolean,
default: false
},
initialSecondary: {
type: Boolean,
default: false
},
date: {
type: Date,
default: Date.now()
}
});
这是配置文件的架构
const ProfileSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: "users"
},
handle: {
type: String,
required: true,
max: 40
},
bio: {
type: String
},
platforms: {
type: [String]
},
website: {
type: String
},
social: {
youtube: {
type: String
},
twitter: {
type: String
},
facebook: {
type: String
},
linkedin: {
type: String
},
twitch: {
type: String
}
},
games: [
{
name: {
type: String
},
platform: {
type: String
},
handle: {
type: String
},
rank: {
type: String
}
}
],
date: {
type: Date,
default: Date.now
}
});
解决方案
遵循正确的变量命名约定
Profile.findOne({ handle: req.params.handle }).then(profile => { // changed name from friends to profile
const newFriend = new Friend({
initialAccepted: true,
initialUser: req.user.id,
secondaryUser: profile.id // changed name from friends to profile
// profile.user.id (ref to user table not provided in schema)
});
如果您提供 profile.user.id 该对象将不会被创建(检查配置文件架构中的 id 但提供了用户 ID)
朋友模式:
secondaryUser: {
type: Schema.Types.ObjectId,
ref: "profile" // checking for id inside profile schema
},
推荐阅读
- python-3.x - 如何在python中使用异步io(快速方式)将数据从一个s3存储桶复制到另一个存储桶?
- r - R中的非线性优化 - 非线性约束
- json - 使用角度解析 Json 响应
- windows - 如何使用 CMD 显示没有父路径的纯文件名
- google-app-engine - 对 gcloud 计算区域的查询描述 us-central1 --flatten='quotas[]' --format='csv[no-heading](quotas.metric,quotas.limit,quotas.usage)'
- javascript - 如何在不重新加载页面的情况下手动设置“this.props.history.location.pathname”的值?
- javascript - jQuery 在 .each 中创建变量引用
- node.js - 虚拟助手机器人框架和控制库
- android - 怎么处理
和类似于 Youtube 的 MotionLayout 中的 onClickListener - html - Vuetify:根据(错误)消息的可见性调整输入字段的底部边距