如何在Firebase中为每个用户存储搜索对象列表及引用?
实现Firebase搜索对象存储与用户引用关联
看起来你想要实现的是将搜索数据独立存储在searches/路径,同时在用户节点中保留对应搜索的引用,这样既可以集中管理所有搜索记录,又能快速关联到发起搜索的用户。我来帮你完善这段代码,实现完整的功能:
完整实现代码
var firebase = require("firebase"); firebase.initializeApp(firebaseConfig); var database = firebase.database(); /* * Inserts a search into the database * @param {string} userId - 发起搜索的用户ID * @param {any} positive - 搜索的正向内容 * @param {any} negative - 搜索的负向内容 * @param {any} neutral - 搜索的中性内容 */ this.addSearchToDB = function(userId, positive, negative, neutral){ let today = new Date(); // 格式化日期为YYYY-MM-DD格式(也可以用toISOString()获取更标准的时间戳) let dateCreated = `${today.getFullYear()}-${String(today.getMonth()+1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`; // 1. 生成一个唯一的搜索ID(用push()自动生成唯一key) const searchRef = database.ref('searches').push(); const searchId = searchRef.key; // 2. 构建完整的搜索对象 const searchData = { positive: positive, negative: negative, neutral: neutral, dateCreated: dateCreated, userId: userId // 也可以在这里关联用户ID,方便反向查询 }; // 3. 批量写入数据(确保两个操作原子性完成) const updates = {}; updates[`/searches/${searchId}`] = searchData; updates[`/users/${userId}/searches/${searchId}`] = true; // 存储引用,用true标记存在即可,也可以存搜索的部分信息 return database.ref().update(updates) .then(() => { console.log("搜索数据和用户引用已成功存储"); return searchId; // 返回生成的搜索ID,方便后续使用 }) .catch((error) => { console.error("存储失败:", error); throw error; }); };
关键细节说明
- 原子性写入:使用
update()方法同时写入searches/和用户节点,避免出现数据不一致的情况(比如写入了搜索记录但用户引用没保存成功)。 - 唯一搜索ID:通过
push()生成的key是Firebase自动生成的,带有时间戳,保证唯一性且按时间排序。 - 用户引用存储:在用户节点下用
searches/${searchId}: true的结构,既节省存储空间,又方便后续查询该用户的所有搜索记录(直接读取/users/${userId}/searches即可拿到所有搜索ID,再根据ID获取完整搜索数据)。 - 日期格式化:用
padStart(2, '0')保证月份和日期是两位数(比如1月变成01,避免出现2024-1-5这种不规范格式),也可以直接用new Date().toISOString()获取标准的ISO时间字符串,更适合数据库存储。
如何调用这个方法
// 假设你有当前用户的ID const currentUserId = "user12345"; addSearchToDB(currentUserId, "happy", "sad", "neutral") .then((searchId) => { // 可以用返回的searchId做后续操作,比如跳转到搜索结果页 }) .catch((err) => { // 处理错误 });
最终你的数据库结构会是这样的(示例):
{ "searches": { "searchKey1": { "positive": "happy", "negative": "sad", "neutral": "neutral", "dateCreated": "2024-05-20", "userId": "user12345" }, "searchKey2": { ... } }, "users": { "user12345": { "searches": { "searchKey1": true, "searchKey3": true }, // 用户其他信息... } } }
内容的提问来源于stack exchange,提问作者Sahand
相关产品推荐
相关产品推荐

