如何获取登录用户数据?

How to get signed in users data?

我有一个 MERN 移动应用程序,它使用 passportjs 来验证和登录用户(使用 mongodb 数据库和 axios),但是,当我最终进入屏幕输入数据时(“日志” ),我无法将 data/log 与登录用户相关联。在他们已经登录以将其与条目相关联之后,我如何在几个屏幕后获取用户 ID?我的 mongodb 数据库有很多用户,所以我只想要特定用户的数据(例如卡路里),即当前登录的用户:

// Mongoose schemas
// log.model.js
const Schema = mongoose.Schema;
const logSchema = new Schema(
    {
        user: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User",
        },
        calories: {
            type: Number,
            required: true,
        },
    },
    {
        timestamps: true,
    }
);
const Log = mongoose.model("Log", logSchema);

// user.model.js
const userSchema = new Schema(
    {
        _id: Schema.Types.ObjectId, // user id
        email: {
            type: String,
            required: true,
            unique: true,
            trim: true,
        },
        password: {
            type: String,
            required: true,
            trim: true,
            minlength: 6,
        },
    },
    {
        timestamps: true,
    }
);
const User = mongoose.model("User", userSchema);

系统首先会提示他们登录该应用,然后他们将导航至主页。尚未添加所有功能,目前处于开发阶段:

// ./frontend/screens/signin.js
function onLoginPress() {
        axios({
            method: "POST",
            data: {
                email: email,
                password: password,
            },
            withCredentials: true,
            url: 'http:localhost:5000/users/signin',
        })
            .then((res) => console.log(res.data))
            .catch((error) =>
                console.log("ERROR: Promise rejected (sign in): " + error)
            );
        navigation.navigate("Home");
}

// ./backend/routes/users.js
router.route("/signin").post((req, res, next) => {
    passport.authenticate("local", (error, user, info) => {
        if (error) {
            res.json({
                status: "FAILED",
                message: error,
            });
        }
        if (!user) {
            res.json({
                status: "FAILED",
                message: "No user exists",
            });
        } else {
            req.logIn(user, (error) => {
                if (error) console.log("ERROR: " + error);
                res.json({
                    status: "SUCCESS",
                    message: "Successfully authenticated",
                });
                console.log(req.user);
            });
        }
    })(req, res, next);
});

他们登录后,他们希望输入卡路里,当他们点击按钮时,我尝试将该日志(以及他们可能添加的任何未来日志)与登录用户相关联:

// ./frontend/screens/log.js
const [calories, setCalories] = React.useState("");

function onSaveLog() {
       axios({
            method: "post",
            url: "http://localhost:5000/log/add",
            data: {
                calories: calories,
                // CANT GET USER ID HERE?
            },
        })
            .then((res) => {
                console.log(res.data);
            })
            .catch(function () {
                console.log("LOG ERROR: promise rejected");
            });
}

// ./backend/routes/log.js
router.route("/add").post((req, res) => {
    const calories = Number(req.body.calories);
    // const user = req.body.user; // CANT GET THE USER ID HERE

    const newLog = new Log({
        calories,
        // user,
    });

    // saves Log data to mongodb
    newLog
        .save()
        .then(() => res.json("Log added"))
        .catch((err) => res.status(400).json("Error: " + err));
});

所以,您怀疑的是,如果我错了请纠正我,您想要一个可以稍后在应用程序中的某个地方访问的 ID 以检索用户数据。

有很多方法可以实现,

  1. 获取id后,可以将其作为Navparams传递。检查此以获取更多信息 RN- params
  2. 接下来您可以将 id 存储在异步存储中并在任何地方检索它,我认为这是最简单的原因 rn--async storage

从“@react-native-async-storage/async-storage”导入 AsyncStorage;

const storeData = async (value) => {
  try {
    await AsyncStorage.setItem('@storage_Key', value)
  } catch (e) {
    // saving error
  }
}

// read
const getData = async () => {
  try {
    const value = await AsyncStorage.getItem('@storage_Key')
    if(value !== null) {
      // value previously stored
    }
  } catch(e) {
    // error reading value
  }
}

你可以这样做,如果你卡住了,请告诉我