【问题标题】:asynchronous issues adding to a map in mongoose在猫鼬中添加到地图的异步问题
【发布时间】:2020-02-29 07:39:12
【问题描述】:

我正在尝试将我的 googleID(对象)添加到另一个猫鼬模式中的地图中。我对我的用户 ID 对象进行字符串化,在我的测试代码中我得到了这个错误:

(node:293528) UnhandledPromiseRejectionWarning: ValidationError: collection validation failed: likes.5dbf6205bdcd5e5f78536447: Cast to ObjectId failed for value "110840542851551561690" at path "likes.$*"
    at new ValidationError (C:\files\node_modules\mongoose\lib\error\validation.js:30:11)
    at model.Document.invalidate (C:\files\node_modules\mongoose\lib\document.js:2333:32)
    at Map.set (C:\files\node_modules\mongoose\lib\types\map.js:71:26)
    at C:\files\app.js:123:30
    at C:\files\node_modules\mongoose\lib\model.js:4589:16
    at C:\files\node_modules\mongoose\lib\query.js:4323:12
    at process.nextTick (C:\files\node_modules\mongoose\lib\query.js:2805:28)
    at process._tickCallback (internal/process/next_tick.js:61:11)
(node:293528) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:293528) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

来自 client.js 的我的 Post 请求:

const likesForm = document.getElementById("test");
likesForm.addEventListener("submit", function (evt) {
  evt.preventDefault();
  console.log(event.target.id)
  const [likeString, itemId] = evt.target.id.split("-");
  vote(
    likeString === "like"
      ? "1"
      : "-1",
    itemId
  );
}, false);

async function vote (voteInc, itemId) {
  const route = `/like/${itemId}`;

  const response = await fetch(route, {
      method: 'POST',
      body: JSON.stringify({"like": voteInc}),
      headers: {
        'Content-Type': 'application/json'
      }
  });

const result = await response.json();

console.log(result);
}

服务器端帖子:

app.post("/like/:id",(req,res)=>{
  const id = req.params.id;
  const like = req.body.like;
  console.log(like);
  console.log(id);
  if(req.isAuthenticated()){
    linkscr.user.findById(req.user.id, (e,foundUser)=>{
      if(e){
        console.log(e);
      }else{
        //if like = 1
        if(like==1){
            linkscr.collection.findById(id, function(error,result){
              if(error){
                console.log(error);
              }else{
                result.likes.set(foundUser._id.toString(),foundUser.googleId);
                result.save();
              }
            })
            console.log("not voted yet. Add 1 and added to like");
        }else{
          linkscr.collection.findById(id, function(error,result){
            if(error){
              console.log(error);
            }else{
              result.dislikes.set(foundUser._id.toString(),foundUser.googleId);
              result.save();
            }
          })
          console.log("not voted yet. Add 1 and added to dislike");   
        };
      };
    });
  }else{
    res.redirect("/");
  }
});

我喜欢/不喜欢的架构:

likes        : { 
  type: Map, 
  of: { 
      type: mongoose.Schema.Types.ObjectId,
      ref: "User" }
    },
dislikes     : { 
  type: Map, 
  of: { 
      type: mongoose.Schema.Types.ObjectId,
      ref: "User" }
    },

Schema 最初是如何保存的:

likes        : {[User._id]:User},
dislikes     : {},

感谢您的任何帮助。你是我唯一的希望 Stack!

我最初认为这是一个关于我如何对待我的对象的猫鼬问题,但看起来这更多地与异步的东西有关。诚然,这是我在撰写本文时编程的最大弱点。

编辑:根据我从文档中看到的内容,猫鼬不能只设置对象字符串。猫鼬不能猫鼬。

编辑 2: 糟糕的是,我在错误的位置输入了错误的 ID。 foundUser._id.toString() ,foundUser

【问题讨论】:

  • linkscr.user.linkscr. collection. 有什么区别? 2个型号不同吗?您可以使用async/await 让它看起来很简单。

标签: javascript asynchronous mongoose maps


【解决方案1】:

为了在猫鼬中创建地图,键**必须是字符串的形式。此外,您的架构(最初未共享)想要 object_id 而不是 google passportID。为了帮助后代,我将在原始帖子中提供编辑。在这种情况下,使用 foundUser 进行简化将起作用。

result.likes.set(foundUser._id.toString(), foundUser);

【讨论】:

  • 仅代码的答案在本网站上通常不受欢迎。您能否编辑您的答案以包含一些 cmets 或对您的代码的解释?解释应该回答这样的问题:它有什么作用?它是如何做到的?它去哪儿了?它如何解决OP的问题?请参阅:How to anwser。谢谢!
  • 道歉。我将编辑我的答案以提供解释。
猜你喜欢
  • 2020-10-16
  • 2014-11-19
  • 2018-01-10
  • 1970-01-01
  • 2021-04-20
  • 1970-01-01
  • 1970-01-01
  • 2021-03-01
  • 2018-08-30
相关资源
最近更新 更多