簡體   English   中英

Model.findById() 返回未定義

[英]Model.findById() is returning undefined

我試圖實現一個最喜歡的切換,它將收藏夾保存在一個數組中,我創建了一個模式和一個路由器,你可以在問題下方看到的代碼是當我嘗試在失眠症上測試它時,我的控制台上沒有定義。日志(最喜歡的)。 我不知道有什么問題。

const userSchema = new Schema({
    username: String,
    email: String,
    password: String,
    favorites: [{ type: Schema.Types.ObjectId, ref: "Places" }],
  },
  {
    timestamps: true,
  });

// 路線

router.put("/favorites/:placeId", (req, res) => {

  const userId = "5ebd13df31430045957db8c3";

  User.findById(userId).then( (user) => {

    const isFavorite = user.favorites.find( (favorite) => {
      return favorite === req.params.placeId;
    });

    console.log(isFavorite);
    console.log(req.params.placeId);

    if (isFavorite) {
      User.findOneAndUpdate(
        { _id: userId },
        {
          $pull: { favorites: req.params.placeId },
        },
        {
          new: true,
        })
        .then((user) => res.json(user))
        .catch((err) => res.status(400).json(err));
    } else {
      User.findOneAndUpdate(
        { _id: userId },
        {
          $push: { favorites: req.params.placeId },
        },
        {
          new: true,
        })
        .then((user) => res.json(user))
        .catch((err) => res.status(400).json(err));
    }
  });
});

這個塊是壞的:

User.findById(userId).then((user) => {
    const isFavorite = user.favorites.find((favorite) => {
      return favorite === req.params.placeId;
    });

而是必須使用 populate():

let favorites = await User.findById(userId).populate('favorites');

然后按 placeId 過濾收藏夾

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM