【问题标题】:How to find JSON entries based on user?如何根据用户查找 JSON 条目?
【发布时间】:2021-10-07 09:25:45
【问题描述】:

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

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

/* user.model.js */
const userSchema = new Schema(
    {
        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);

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

/* log.model.js */
const logSchema = new Schema(
    {
        minutesRead: {
            type: number,
            required: true,
        },
        date: {
            type: Date,
            required: true,
        },
    },    
    {
        timestamps: true,
    }
);
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>
    )
};

【问题讨论】:

    标签: mongodb react-native express mongoose axios


    【解决方案1】:

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

    在我看来,最好的方法是在 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。

    【讨论】:

    • 所以后端应该对分钟读取(在示例中)进行求和计算?目前我有前端,如您所见。然后前端如何访问 res.json({totalMinutes}) 的 totalMinutes ?
    • 您可以在前端或后端执行此操作,这取决于您。如果你在后端做,在前面你可以做 setMinutes 到 response.totalMinutes。如果你想在前面做,那么你必须传递所有的文件,所以 res 就像 res.json({ data: logs })
    • 感谢 Nacho,但它仍然无法正常工作。我认为问题在于我不明白为什么当他们(应用程序的实际用户)没有在前端输入该数据时我会“在正文中传递用户的 ID”。他们永远不会被提示提供该信息。如果我在尝试时 console.log() 那个变量,它是未定义的,正如我所期望的那样。我当然假设您的意思是router.route('/add').post()部分中的const user = req.body.user。
    • 您可以在用户登录时在响应中获取用户ID。另一种方法是使用用户的电子邮件。在你的logSchema:email: { type: string }。然后在getTotalMinutes:const logs = await Log.find({ email: req.params.user })
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 2021-11-24
    相关资源
    最近更新 更多