如何根据用户查找 JSON 条目?

在 MERN iOS react-native 应用程序中,如何根据登录的用户(即电子邮件)在 Mongodb 图集中查询正确的 JSON 条目?一个基本特征。举个具体的例子,找出登录用户(电子邮件)当天阅读了多少(minutesRead),然后在移动应用程序的前端将其发送回给他们。相关代码如下:

在登录时,他们填写以下内容(猫鼬模式):

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

现在,在登录后的应用程序中,他们可以填写以下条目(猫鼬模式):

/* log.model.js */
const logSchema = new Schema(
    {
        minutesRead: {
            type: number,date: {
            type: Date,}
);
const Log = mongoose.model("Log",logSchema);

这是我记录分钟阅读的路线:

const Log = require("../models/log.model");

router.route("/add").post((req,res) => {
    const minutesRead = req.body.minutesRead;
    // ..etc

    const newLog = new Log({ minutesRead,/* ..etc */ });

    newLog.save().then(() => res.json("Log added")).catch(error => //throw error);
}

现在在前端显示登录用户的特定分钟读取数据:

/* Home.js screen */
const url = "http://localhost....";

const home = ({ navigation }) => {
    const [totalMinutesRead,setMinutes] = React.useState("");

    axios.get(url).then(response => {
       setMinutes(() => { 
           /* sum all of user's minutesRead entries in a loop here */
       });
    });

    return (
        <View>
            <Text>{totalMinutesRead}</Text>
        </View>
    )
};
jiba1023 回答:如何根据用户查找 JSON 条目?

您需要一种方法来知道哪个日志来自哪个用户。

我认为最好的方法是在 logSchema 中添加一个 user 字段:

user: {
    type: mongoose.Schema.Types.ObjectId,ref: 'User'
}]

在你的

记录分钟的路由读取

您需要在正文中传递用户的 id。

然后,要获得 totalMinutesRead,您必须执行类似操作以按用户 ID 进行过滤。

router.route('getTotalMinutes/:user').get(async (req,res) => {
    const logs = await Log.find({ user: req.params.user });

    const totalMinutes = logs.reduce((total,log) => total + log.minutesRead,0);

    res.json({ totalMinutes });
}

最后在 react-native 中确保您在 url 中传递您的用户 ID。

本文链接:https://www.f2er.com/412.html

大家都在问