mongoose关注/追随者

我正在尝试为nodejs / mongoose驱动的网站添加以下/ followersfunction。 我正在使用下面的方法正确存储ID的问题。 不太清楚发生了什么问题,但似乎只是将ID保存到下面的部分,而不是更新第一部分的追随者。

我知道,如果用户ID只是传递到发布请求会很容易,但我认为将用户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(); }); }); }); 

用户模型看起来像这样

 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' }], }); 

任何有关这方面的见解将不胜感激。

从我可以看到你的schemafollowingfollowers和一个ObjectId's数组而不是ObjectId本身,所以你需要push _id push入数组,而不是将其值设置为_id

另外,在savecallback进行第二次update 。 这样,您可以在两个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 } }); }); } }); }); 

我希望这可以帮助你!