fix: correct cloud upsert — query then update/add per user

Before: add-first-then-update caused duplicate docs on each push
because add() always succeeds once collection exists.

Now: query {_openid} first → update if found, add if not.
Each user always has exactly one document in plank_data.

Also removed debug console.log — only production-scale errors remain.
This commit is contained in:
2026-06-04 17:41:29 +08:00
parent 6f33dd54c0
commit 90e0e64156
+13 -26
View File
@@ -16,9 +16,7 @@ const init = () => {
try {
wx.cloud.init({ env: 'cloudbase-d1g56kl2q8f4f7d8a', traceUser: true })
_enabled = true
console.log('[cloud] init ok')
} catch (e) {
console.error('[cloud] init failed:', e)
_enabled = false
}
}
@@ -27,14 +25,11 @@ const pullAll = async () => {
const db = getDb()
if (!db) return null
try {
console.log('[cloud] pulling data...')
const res = await db.collection(DB_COLLECTION)
.where({ _openid: '{openid}' })
.get()
console.log('[cloud] pull result:', res.data.length, 'docs')
return res.data.length > 0 ? res.data[0] : null
return (res && res.data && res.data.length > 0) ? res.data[0] : null
} catch (e) {
console.warn('[cloud] pull skipped (collection may not exist yet):', e.errMsg || e.message)
return null
}
}
@@ -48,7 +43,6 @@ const pushAll = () => {
const _doPush = async () => {
const db = getDb()
if (!db) return
console.log('[cloud] pushing data...')
try {
const storage = require('./storage')
const themeMod = require('./theme')
@@ -61,25 +55,19 @@ const _doPush = async () => {
updatedAt: db.serverDate()
}
try {
const addRes = await db.collection(DB_COLLECTION).add({ data })
console.log('[cloud] push ok (new doc):', addRes._id)
} catch (addErr) {
console.log('[cloud] add returned error, trying update...')
const existing = await db.collection(DB_COLLECTION)
.where({ _openid: '{openid}' })
.get()
if (existing && existing.data && existing.data.length > 0) {
await db.collection(DB_COLLECTION)
.doc(existing.data[0]._id)
.update({ data })
console.log('[cloud] push ok (updated doc):', existing.data[0]._id)
} else {
console.error('[cloud] push failed: no doc found to update')
}
// Query then upsert: one doc per user
const existing = await db.collection(DB_COLLECTION)
.where({ _openid: '{openid}' })
.get()
if (existing && existing.data && existing.data.length > 0) {
await db.collection(DB_COLLECTION)
.doc(existing.data[0]._id)
.update({ data })
} else {
await db.collection(DB_COLLECTION).add({ data })
}
} catch (e) {
console.error('[cloud] push error:', e.errMsg || e.message)
// Silently retry on next write
}
}
@@ -94,10 +82,9 @@ const clearAll = async () => {
await db.collection(DB_COLLECTION)
.doc(existing.data[0]._id)
.remove()
console.log('[cloud] cleared')
}
} catch (e) {
console.warn('[cloud] clear skipped:', e.errMsg || e.message)
// Nothing to clear
}
}