use*_*457 2 mongoose mongodb node.js express
我正在尝试为 nodejs/mongoose 驱动的网站添加关注者/关注者功能。我在使用以下方法正确存储 ID 时遇到问题。不太确定出了什么问题,但似乎只将 ID 正确保存到以下部分,但没有更新第一部分的关注者。
我知道如果用户 ID 只是传递给 post 请求会很容易,但我认为将用户 ID 存储在前端是一种安全问题,所以只使用用户名来获取 ID 会更好。
// Handles the post request for following a user
router.post('/follow-user', function(req, res, next) {
// First, find the user from the user page being viewed
User.findOne({ username: req.body.username }, function(err, user) {
// Add to users followers with ID of the logged in user
user.followers = req.user._id;
// Create variable for user from page being viewed
var followedUser = user._id;
// Save followers data to user
user.save();
// Secondly, find the user account for the logged in user
User.findOne({ username: req.user.username }, function(err, user) {
// Add the user ID from the users profile the follow button was clicked
user.following = followedUser;
// Save following data to user
user.save();
});
});
});
Run Code Online (Sandbox Code Playgroud)
用户模型看起来像这样
var userSchema = new Schema({
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
email: { type: String, required: true },
avatar: { type: String },
bio: { type: String },
following: [{ type: Schema.ObjectId, ref: 'User' }],
followers: [{ type: Schema.ObjectId, ref: 'User' }],
});
Run Code Online (Sandbox Code Playgroud)
对此的任何见解将不胜感激。
从我可以在你看到schema
,following
与followers
和数组ObjectId's
,而不是ObjectId
它本身,所以你需要push
在_id
进入阵列,而不是它的值设置为_id
。
另外,做第二次update
在callback
的save
。通过这种方式,您可以updates
在成功完成后将响应发送回前端。
尝试这个:
User.findOne({ username: req.body.username }, function(err, user) {
user.followers.push(req.user._id);
var followedUser = user._id;
user.save(function(err){
if(err){
//Handle error
//send error response
}
else
{
// Secondly, find the user account for the logged in user
User.findOne({ username: req.user.username }, function(err, user) {
user.following.push(followedUser);
user.save(function(err){
if(err){
//Handle error
//send error response
}
else{
//send success response
}
});
});
}
});
});
Run Code Online (Sandbox Code Playgroud)
我希望这可以帮助你!
我设法follow/unfollow
通过设置两个路由而不是一个路由来在我的 Node REST API 上实现该功能:
对于关注请求:
following
数组中添加了您要关注的用户的 IDfollowers
您要关注的用户的数组中对于取消关注请求:
following
数组中删除了要取消关注的用户的 IDfollowers
您要取消关注的用户数组中删除您的 ID
authenticate
是我的自定义中间件
id
params 是您尝试关注/取消关注的用户的 IDres.user 是从“authenticate”中间件返回的,请不要我的回答。
router.patch('/follow/:id', authenticate, async (req, res) => {
try {
const id = new ObjectID(req.params.id)
// check if the id is a valid one
if (!ObjectID.isValid(req.params.id)) {
return res.status(404).json({ error: 'Invalid ID' })
}
// check if your id doesn't match the id of the user you want to follow
if (res.user._id === req.params.id) {
return res.status(400).json({ error: 'You cannot follow yourself' })
}
// add the id of the user you want to follow in following array
const query = {
_id: res.user._id,
following: { $not: { $elemMatch: { $eq: id } } }
}
const update = {
$addToSet: { following: id }
}
const updated = await User.updateOne(query, update)
// add your id to the followers array of the user you want to follow
const secondQuery = {
_id: id,
followers: { $not: { $elemMatch: { $eq: res.user._id } } }
}
const secondUpdate = {
$addToSet: { followers: res.user._id }
}
const secondUpdated = await User.updateOne(secondQuery, secondUpdate)
if (!updated || !secondUpdated) {
return res.status(404).json({ error: 'Unable to follow that user' })
}
res.status(200).json(update)
} catch (err) {
res.status(400).send({ error: err.message })
}
})
router.patch('/unfollow/:id', authenticate, async (req, res) => {
try {
const { id } = req.params
// check if the id is a valid one
if (!ObjectID.isValid(id)) {
return res.status(404).json({ error: 'Invalid ID' })
}
// check if your id doesn't match the id of the user you want to unfollow
if (res.user._id === id) {
return res.status(400).json({ error: 'You cannot unfollow yourself' })
}
// remove the id of the user you want to unfollow from following array
const query = {
_id: res.user._id,
following: { $elemMatch: { $eq: id } }
}
const update = {
$pull: { following: id }
}
const updated = await User.updateOne(query, update)
// remove your id from the followers array of the user you want to unfollow
const secondQuery = {
_id: id,
followers: { $elemMatch: { $eq: res.user._id } }
}
const secondUpdate = {
$pull: { followers: res.user._id }
}
const secondUpdated = await User.updateOne(secondQuery, secondUpdate)
if (!updated || !secondUpdated) {
return res.status(404).json({ error: 'Unable to unfollow that user' })
}
res.status(200).json(update)
} catch (err) {
res.status(400).send({ error: err.message })
}
})
Run Code Online (Sandbox Code Playgroud)