为什么secondaryUser字段会影响findOne的正常工作?

时间:2019-03-15 01:38:24

标签: node.js express mongoose

在此,我将nodejs与express和mongoose一起使用。我的问题是,更改secondaryUser字段如何影响findOne是否起作用?如果我将其作为friends.id使用,它将可以找到正确的配置文件,但我想将其绑定到配置文件中的用户字段。如果我将其更改为friends.user.id,则findOne失败,并在捕获中发送404错误。

router.post(
  "/:handle",
  passport.authenticate("jwt", {
    session: false
  }),
  (req, res) => {
    Profile.findOne({ handle: req.params.handle }).then(friends => {
      const newFriend = new Friend({
        initialAccepted: true,
        initialUser: req.user.id,
        secondaryUser: friends.id
      });

      newFriend
        .save()
        .then(Friend => res.json(Friend))
        .catch(err =>
          res.status(404).json({
            friendnotfound: "No people found with that handle"
          })
        );
    });
  }
);

用于朋友的模式是

const FriendSchema = new Schema({
  initialUser: {
    type: Schema.Types.ObjectId,
    ref: "profile"
  },

  secondaryUser: {
    type: Schema.Types.ObjectId,
    ref: "profile"
  },

  initialAccepted: {
    type: Boolean,
    default: false
  },

  initialSecondary: {
    type: Boolean,
    default: false
  },

  date: {
    type: Date,
    default: Date.now()
  }
});

这是配置文件的架构

const ProfileSchema = new Schema({
  user: {
    type: Schema.Types.ObjectId,
    ref: "users"
  },
  handle: {
    type: String,
    required: true,
    max: 40
  },
  bio: {
    type: String
  },
  platforms: {
    type: [String]
  },
  website: {
    type: String
  },

  social: {
    youtube: {
      type: String
    },
    twitter: {
      type: String
    },
    facebook: {
      type: String
    },
    linkedin: {
      type: String
    },
    twitch: {
      type: String
    }
  },

  games: [
    {
      name: {
        type: String
      },
      platform: {
        type: String
      },
      handle: {
        type: String
      },
      rank: {
        type: String
      }
    }
  ],

  date: {
    type: Date,
    default: Date.now
  }
});

1 个答案:

答案 0 :(得分:0)

遵循正确的变量命名约定

Profile.findOne({ handle: req.params.handle }).then(profile => { // changed name from friends to profile
    const newFriend = new Friend({
        initialAccepted: true,
        initialUser: req.user.id,
        secondaryUser: profile.id // changed name from friends to profile
        // profile.user.id (ref to user table not provided in schema)
    });

如果提供profile.user.id,则不会创建该对象(检查配置文件架构中的ID,但提供用户ID)

朋友模式:

 secondaryUser: {
        type: Schema.Types.ObjectId,
        ref: "profile" // checking for id inside profile schema
      },