【问题标题】:How can I remove bookmarked posts of user (1) from user (2) tab after user (1) deletes his account?用户 (1) 删除其帐户后,如何从用户 (2) 选项卡中删除用户 (1) 的书签帖子?
【发布时间】:2022-01-11 08:58:03
【问题描述】:

在为社交媒体网络应用程序创建 node.js、express、mongoDb REST api 后,几乎所有基本的社交媒体操作(登录、注册、添加帖子、删除帖子、删除帐户、关注用户......) , 我目前面临一个问题,在实现为帖子添加书签功能后,在第一个用户删除他的帐户后,我无法想出解决方案来从另一个用户的书签帖子页面中删除书签帖子。我将在下面提供我的代码: (附注:书签是用户模型中的一个数组。我还想提一下我最初打算用于该任务的步骤:

  1. 通过ID获取当前用户

  2. 然后获取这个用户创建的所有帖子,它返回一个数组,所以我映射它来获取每个帖子的id

  3. 之后,我获取了应用程序中的所有用户,最初打算将每个用户内部的书签数组中的帖子与当前用户创建的帖子进行比较。然后我会从每个用户的书签数组中提取这些相同的帖子。 --> 我认为我分析的逻辑是可维护的,但它对我不起作用。这是下面的代码:

    export const deleteUser = async (req, res) => { 试试 {

     let user = await User.findById(req.params.userId)
    
         const userPosts = await Post.find({ creatorId: user._id })
    
         const allUsers = await User.find()
         const myPostsIds = userPosts.map((post) => post._id.toString())
    

//这是我为我的任务实现的部分,但显然 有什么不对的地方

        await Promise.all(
            myPostsIds.forEach((id) =>
                allUsers.map((user) => {
                    user.bookmarks.includes(id) &&
                        user.updateOne({ $pull: { bookmarks: id } })
                })
            )
        )

        await Post.deleteMany({ creatorId: user._id })
        await user.remove()
        
        res.status(200).json({
            message: "Account has been deleted successfully!",
        })
    
} catch (err) {
    errorHandler(res, err)
}

}

【问题讨论】:

  • Promise.all 需要一个 promise 数组,但 forEach 不会返回任何内容,请改用 map 并确保返回 Promise 或异步函数。
  • 当用户删除一个特定帖子时,我使用了相同的策略,然后这个特定帖子会从其他用户的所有书签页面中删除。使用相同的 Promise.all 可以 100% 工作,因为 updateOne() 是一个 mongoDB 异步函数,它是一个承诺(期望等待)。这里的不同之处在于我没有以前的情况下的单个帖子 ID,这里是该用户创建的帖子数组。我已经尝试了所有可能的情况,但我认为我只是错过了一些东西。
  • Promise.all 如果您使用未定义的参数调用它,将抛出 TypeError (TypeError: undefined is not iterable)。 (拨打Promise.all(undefined)试试看)。
  • 是的,谢谢。我明白了你的意思,但是用 map 替换 forEach 对我来说并不奏效。我很确定这是导致该功能无法正常工作的一个小问题。在这一点上变得令人沮丧????

标签: javascript node.js mongodb web-development-server


【解决方案1】:

正如我的 cmets 中所述,您传递给 Promise.all 的值不是 Promise 数组/异步函数数组。

第二个错误是在(当前)forEach 函数中的 .map(),您在 map-call 中没有返回任何内容。

所以应该这样做:

// first convert all ids to a promise
await Promise.all(myPostsIds.map(id => new Promise(resolve => {
  // during this, await every test and update
  return Promise.all(allUsers.map(user => new Promise(resolve => {
    // if it includes the id, cast the update and then resolve
    if (user.bookmarks.includes(id)) {
      // if found, resolve the promise for this user after the change
      user.updateOne({ $pull: { bookmarks: id } }).then(resolve)
    } else { 
      // resolve directly if not found.
      resolve()
    }
  // when all users are done for this id, resolve the Promise for the given id
  }))).then(resolve)
})))

一个更容易阅读和更短的方法是:

for (const id of myPostIds) {
  for (const user of allUsers) {
    if (user.bookmarks && user.bookmarks.includes(id)) {
      await user.updateOne({ $pull: { bookmarks: id } });
    }
  }
}

【讨论】:

    猜你喜欢
    • 2019-12-01
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多