MongoDB _id时间戳时效性判断及Node.js网站JSON数据库功能开发咨询
嘿,刚入门就能想着给社区贡献,必须给你点个赞!针对你提到的两个功能需求,我整理了具体的实现思路和代码示例,你可以参考下:
功能一:检查表单提交账号是否存在于JSON数据库
首先得明确你的“JSON数据库”是本地JSON文件还是内存中维护的JSON对象?这里给出两种常见场景的实现:
场景1:JSON数据存储在本地文件中
如果是读取本地JSON文件校验,用Node.js的fs模块异步读取解析后匹配即可:
const fs = require('fs').promises; const path = require('path'); // 假设JSON文件路径为 ./data/users.json,格式示例:{ "users": ["alice", "bob", "charlie"] } async function checkAccountExists(account) { try { const filePath = path.join(__dirname, 'data', 'users.json'); const fileContent = await fs.readFile(filePath, 'utf8'); const data = JSON.parse(fileContent); // 根据你的JSON结构调整匹配逻辑,比如数组用includes,对象则遍历键值对 return data.users.includes(account); } catch (error) { console.error('读取JSON文件失败:', error); throw error; // 也可根据业务需求返回false或自定义错误处理 } } // 在表单提交路由中调用 app.post('/submit-account', async (req, res) => { const submittedAccount = req.body.account; const exists = await checkAccountExists(submittedAccount); res.send(exists ? '账号已存在' : '账号不存在'); });
注意:如果JSON文件频繁修改或数据量较大,频繁读文件会有性能瓶颈,后续可以考虑把数据缓存到内存,或者直接迁移到MongoDB这类数据库。
场景2:JSON数据已加载到内存中
如果启动时就把JSON数据加载到了内存(比如全局变量),校验逻辑会更简单:
// 启动时加载JSON到内存 let userData = require('./data/users.json'); function checkAccountExists(account) { return userData.users.includes(account); } // 路由中调用 app.post('/submit-account', (req, res) => { const submittedAccount = req.body.account; const exists = checkAccountExists(submittedAccount); res.send(exists ? '账号已存在' : '账号不存在'); });
功能二:基于MongoDB _id中的时间戳判断是否在最近24小时内
MongoDB的_id是ObjectId类型,前4个字节就是文档创建时的Unix时间戳(单位秒)。不管用原生驱动还是Mongoose,都能直接提取这个时间:
原生MongoDB驱动实现
const { ObjectId } = require('mongodb'); function isAccessedInLast24Hours(docId) { // 将_id字符串转为ObjectId实例 const objectId = new ObjectId(docId); // 获取_id对应的创建时间(Date对象) const createdAt = objectId.getTimestamp(); // 计算24小时前的时间点 const twentyFourHoursAgo = new Date(Date.now() - 24 * 60 * 60 * 1000); // 判断是否在24小时范围内 return createdAt >= twentyFourHoursAgo; } // 使用示例:假设从数据库拿到的文档_id是 '60d21b4667d0d8992e610c85' const docId = '60d21b4667d0d8992e610c85'; const isRecent = isAccessedInLast24Hours(docId); console.log(isRecent ? '数据在24小时内被创建/访问' : '数据超过24小时未更新');
Mongoose实现
如果用Mongoose,文档的_id本身就是ObjectId实例,直接调用getTimestamp()即可:
// 假设你的Mongoose模型是 User const User = require('./models/User'); async function checkUserAccessTime(userId) { const user = await User.findById(userId); if (!user) { throw new Error('用户不存在'); } const createdAt = user._id.getTimestamp(); const twentyFourHoursAgo = new Date(Date.now() - 24 * 60 * 60 * 1000); return createdAt >= twentyFourHoursAgo; }
补充:如果你的“访问时间”指的是用户最后一次访问的时间,而非文档创建时间,建议在MongoDB文档中单独加一个lastAccessedAt字段,这样判断会更准确——毕竟_id的时间戳只是文档创建时间,不是最后访问时间哦!
内容的提问来源于stack exchange,提问作者code4meplz
相关产品推荐
相关产品推荐

