Firebase数据库查询报错TypeError: obj.hasOwnProperty is not a function求助
Hey there, let's break down this frustrating error you're hitting with your Firebase Admin database calls. That TypeError: obj.hasOwnProperty is not a function almost always points to Firebase encountering a non-standard JavaScript object during data validation—even when you're just reading data, the issue might tie back to how you're using the result afterward.
Common Causes & Fixes
1. Your retrieved data contains non-native JS objects
Firebase's validation logic expects plain JavaScript objects. If your /crawls records include custom class instances, Proxy objects, or Firebase-specific types (like older Timestamp objects that aren't properly serialized), Firebase will throw this error when processing the data.
Fix: Convert the snapshot value to a pure JSON object to strip any non-standard wrappers:
const lastCrawl = admin .database() .ref('/crawls') .orderByChild("dateAdded") .limitToLast(1) .once('value') .then((snapshot) => { // Serialize and deserialize to get a plain JS object const rawData = snapshot.val(); return rawData ? JSON.parse(JSON.stringify(rawData)) : null; });
2. Outdated Firebase Admin SDK version
Older versions of the SDK had bugs in the data validation logic that could trigger this error even with valid data.
Fix: Update to the latest stable version:
npm install firebase-admin@latest --save
3. Accidental modification of object prototype (unlikely but possible)
If any code in your project overwrites Object.prototype.hasOwnProperty (a risky practice!), Firebase's internal logic will break. Double-check your global code for lines like this:
// Avoid this kind of global prototype modification! Object.prototype.hasOwnProperty = function() { ... }
4. Try an alternative way to read the snapshot
For limitToLast(1), the returned snapshot contains a single child node. Using forEach to extract the child value can sometimes bypass issues with direct val() calls:
const lastCrawl = admin .database() .ref('/crawls') .orderByChild("dateAdded") .limitToLast(1) .once('value') .then((snapshot) => { let latestRecord = null; // Iterate through the single child node snapshot.forEach(childSnapshot => { latestRecord = childSnapshot.val(); }); return latestRecord; });
Quick Isolation Test
To narrow down the issue, log the raw snapshot data before returning it:
.then((snapshot) => { console.log("Raw snapshot data:", snapshot.val()); console.log("Type of data:", typeof snapshot.val()); return snapshot.val(); });
If the logged data looks like a plain object but you still get the error, the problem is almost certainly in how you're using the lastCrawl promise result later (e.g., writing it back to Firebase without proper serialization).
内容的提问来源于stack exchange,提问作者João Marcelo Martins

