我想制作一个小型全栈家庭项目。如果项目进展顺利,我想在申请工作时将其添加到我的作品集中。我的计划是使用 MERN 堆栈构建一个网络应用程序,用户可以在其中创建自己的登录名、存储他们拥有的花以及需要多久浇水一次。下一步是制定浇水计划。
我刚刚开始使用 mongoDB。我想知道如何最好地构建数据,因为不同的用户应该有权访问自己的花。
是否可以将花和关联的用户放在同一个 MongoDB 文档中?
是否可以链接类似于 SQL 数据库的文档?
以下是我使用第一种替代方案的方法:
{
name: "Joe Flowerman",
flowers: [
{
name: "Freesia",
water_freq_month: 4
},
{
name: "Boat orchid",
water_freq_month: 8
}
]
}
我不确定这是否是此类数据的最佳使用方式,所以我欢迎任何意见。
最佳答案
这两种选择都是可能的。
如果您需要显示用户和他们的鲜花,将鲜花嵌入用户内部就可以了。
但是如果您需要显示所有花朵,最好将花朵保存在单独的文档中。
假设您不需要显示所有花朵,并选择嵌入。
您可以为用户创建以下 Mongoose 架构:
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
flowers: [
new mongoose.Schema({
name: {
type: String,
required: true
},
water_freq_month: {
type: Number,
required: true
}
})
]
});
module.exports = mongoose.model("User", userSchema);
可以为用户添加鲜花,并通过以下代码获取带有鲜花的用户信息:
const router = require("express").Router();
const User = require("../models/user");
router.post("/users/flowers", async (req, res) => {
const loggedUserId = "5ddbcaaf7b9b9c4b986f9e89";
const { name, water_freq_month } = req.body;
const result = await User.findByIdAndUpdate(
loggedUserId,
{
$push: {
flowers: { name, water_freq_month }
}
},
{ new: true }
);
res.send(result);
});
router.get("/users/flowers", async (req, res) => {
const loggedUserId = "5ddbcaaf7b9b9c4b986f9e89";
const user = await User.findById(loggedUserId);
res.send(user);
});
module.exports = router;
当我们向用户添加两朵花时,当我们获取用户时,响应将如下所示:
{
"_id": "5ddbcaaf7b9b9c4b986f9e89",
"name": "Joe Flowerman",
"flowers": [
{
"_id": "5ddbcacc1640bf4b10f985cb",
"name": "Freesia",
"water_freq_month": 4
},
{
"_id": "5ddbcafba209c91b5cbf3b4c",
"name": "Boat orchid",
"water_freq_month": 8
}
],
"__v": 0
}
关于node.js - 具有不同库存的用户的 MongoDB 数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59029900/