hydrogen-js-sdk is the same SDK file Bmob-<version>.min.js supports all of the following host environments, with no platform-specific code branches:
- Browser / any Web frontend (React, Vue 2, Vue 3, Next.js, Nuxt, Vite, Astro, SvelteKit, Solid, etc.)
- Node.js server (must be imported from source)
- WeChat Mini Program / Alipay / ByteDance / QQ / Baidu Mini Programs
- Quick App
- Cocos Creator JS
- Electron / Tauri
- Any hybrid App (H5 embedded in WebView)
This skill only covers the new hydrogen-js-sdk(
Bmob.Query('X')Promise style, 3.0+). The old Backbone.js-basedbmob-min.js(Bmob.Object.extend("X")callback style)do not use it, and do not fall back。
Core Principles
1. Initialization supports two methods(hydrogen-js-sdk 3.0+ both are compatible; choose one according to the scenario,do not mix them):
Method A — Secret Key + API security code(Recommended: browser / Mini Program / public clients, the SDK internally uses encrypted authorization):
Bmob.initialize("你的Secret Key", "你的API 安全码");
- Secret Key: Console → App → Settings → App Keys → Secret Key。
- API security code: Console → App → App Feature Settings → Security Verification → API security code set it yourself.
Method B — Application ID + REST API Key(officially compatible since 3.0; suitable for migrating existing 1.x/2.x projects, or sharing the same set of Keys with the server-side REST):
Bmob.initialize("你的Application ID", "你的REST API Key");
- Application ID / REST API Key: Console → App → Settings → App Keys, same page.
- The REST API request domain is generally
https://api.codenow.cn(seebmob-database-restful)。
In the 2.x era, Method B had limited functionality;3.0+ makes the two initialization methods equivalent and usable. Public bundles should still prefer Method A (the REST API Key can be captured via packet sniffing).
2. Do not commit real keys into git; do not hardcode the SDK version number in CDN / dist. Use environment variables for keys (Vite import.meta.env.VITE_BMOB_*、Next.js process.env.NEXT_PUBLIC_BMOB_*, injection during Mini Program build, etc.). The dist file name is Bmob-<version>.min.js, use npm install hydrogen-js-sdkwhen there is a bundler; for pure CDN browser scenarios, use the jsDelivr API to dynamically fetch tags.latest and then concatenate the URL (see references/platform-init.md)。Forbiddento write @2.7.3 in examples, as such specific versions will expire.
3. By default, queries return 100 records, with a maximum of 1000. If you need more, use skip + limit pagination or use BQL (bmob-bql skill)。
4. Three reserved fields cannot be written manually:objectId、createdAt、updatedAt. When reading objectId, use res.objectId(not id)。
5. Precision of time field comparison:createdAt / updatedAt is microsecond precision on the server; when doing time comparisons at the application layer, add 1 second.
Security Checklist
- Key tiering: browser / Mini Program / mobile clients should prefer Secret Key + API security code(Method A),never use Master Key. If using Application ID + REST API Key (Method B), the REST API Key will be exposed in the bundle.
- Disable debug mode in production:
Bmob.debug(true)is only used during Mini Program development; delete it before release. - The mini program must configure a server domain whitelist: WeChat backend
requestAdd at least the legal domainhttps://api.bmobcloud.com(seereferences/platform-init.mdWeChat mini program section). - If a WeChat mini program uses npm to import the SDK, you must first run "Tools --> Build npm" in the developer tools: if not built,
import Bmob from "hydrogen-js-sdk"will not take effect. - Tables written to must have ACLs configured: otherwise any user can modify any row. See
bmob-acl-and-roles(P1)。 - Batch operation limit is 50 records(including batch update and batch delete). If exceeded, you need to loop.
- Batch query limit is 100 records / 1000 records per call: avoid pulling the entire table at once.
-
Bmob.User.loginIn the mini program you must first callwx.login()to get the code, otherwise the session cannot obtain sessionToken.
FAQ
Cross-platform Q&A:shared/faq.md(routing, keys, MCP, Pointer format, etc.).
Anti-patterns
See shared/anti-patterns.md. Key points for this platform: do not mix the old version Bmob.Object.extend; do not mix the two kinds of initialize; do not use the minified entry in Node.
Quick Start (80% of cases are written like this)
Initialization
Recommended by default Method A(Secret Key + API security code); 3.0+ can also use Method B(Application ID + REST API Key), see the core principles above.
import Bmob from "hydrogen-js-sdk";
Bmob.initialize("你的Secret Key", "你的API 安全码");
// 或:Bmob.initialize("你的Application ID", "你的REST API Key");
For the detailed 8 host environment import methods, see references/platform-init.md。
Add a row
const query = Bmob.Query("GameScore");
query.set("score", 1337);
query.set("playerName", "bmob");
query.set("cheatMode", false);
query.save().then((res) => {
console.log(res.objectId, res.createdAt);
});
Get a row by objectId
const query = Bmob.Query("GameScore");
query.get("7ecd253a25").then((res) => {
console.log(res);
});
Update a row
const query = Bmob.Query("GameScore");
query.set("id", "7ecd253a25"); // 注意 set("id", objectId)
query.set("score", 9999);
query.save().then((res) => {
console.log(res.updatedAt);
});
Delete a row
const query = Bmob.Query("GameScore");
query.destroy("7ecd253a25").then((res) => {
console.log(res); // { msg: "ok" }
});
Delete the value of a field
const query = Bmob.Query("GameScore");
query.get("7ecd253a25").then((res) => {
res.unset("cover");
res.save();
});
Query all (default 100 records)
const query = Bmob.Query("GameScore");
query.find().then((res) => {
console.log(res);
});
Conditional query
equalTo(field, op, value),op can be "==" / "!=" / ">" / ">=" / "<" / "<="。
const query = Bmob.Query("GameScore");
query.equalTo("score", ">", 100);
query.equalTo("cheatMode", "==", false); // 多个条件 = AND
query.limit(20);
query.skip(0);
query.order("-score"); // 降序
query.find().then(console.log);
OR query
const query = Bmob.Query("GameScore");
const q1 = query.equalTo("score", ">", 150);
const q2 = query.equalTo("score", "<", 5);
query.or(q1, q2);
query.find().then(console.log);
Select only some fields
const query = Bmob.Query("Post");
query.select("title");
query.find().then(console.log);
Collection query
query.containedIn("playerName", ["Bmob", "Codenow", "JS"]);
query.notContainedIn("playerName", ["spam"]);
query.exists("score"); // 含此字段
query.doesNotExist("score"); // 不含此字段
Count
const query = Bmob.Query("diary");
query.count().then((n) => console.log(`共 ${n} 条`));
query.count(100).then((arr) => console.log("最多返回 100 条记录数据 + count"));
Atomic counter
const query = Bmob.Query("Post");
query.get("objectId").then((res) => {
res.increment("likes"); // +1
res.increment("likes", 5); // +5(支持负数)
res.save();
});
Array fields
const query = Bmob.Query("Diary");
query.add("DiaryType", ["public"]); // 末尾追加
query.addUnique("DiaryType", ["secret"]); // 去重追加
query.save();
query.get("objectId").then((res) => {
res.remove("DiaryType", ["secret"]); // 删除元素
res.save();
});
Advanced capabilities (read references/ as needed)
| Topic | Path |
|---|---|
| End-to-end scenarios (blog, mini program login, Todo ACL, etc.) | shared/recipes/ |
| Initialization differences across 8 host environments (browser / Node / WeChat/Alipay/Bytedance/QQ/Baidu mini programs / Quick App / Cocos Creator / Electron) | references/platform-init.md |
| BmobDocs sync code snippets | references/snippets/ |
| Pointer / Relation one-to-many / many-to-many | references/pointer-and-relation.md |
Complex subqueries ($inQuery / $notInQuery), fuzzy queries, geolocation queries |
references/query.md |
| Real-time data subscription (mini programs / Web only) + WebSocket | references/realtime.md |
| Batch operations (≤ 50) | references/batch.md |
Integration with MCP
If the user has configured in the IDE Bmob MCP,Before writing code, first call get_project_tables to get the real schema, avoiding:
- Misspelled field names (schemaless does not report errors, and troubleshooting after data enters the database is very slow)
- Wrong field type for Pointer (must be
{"__type":"Pointer","className":"X","objectId":"..."}) - Writing reserved fields as business fields
sequenceDiagram
autonumber
participant Dev as Developer
participant Agent as Agent
participant MCP as bmob-mcp
participant Code as bmob-database-javascript
Dev->>Agent: "Next.js 项目里加 Bmob 文章列表"
Agent->>MCP: get_project_tables()
MCP-->>Agent: {Article: {title:String, content:String, author:Pointer(_User)}}
Agent->>Code: 按真实 schema 生成 Bmob.Query("Article") 代码
Code-->>Dev: 完整可运行代码(含 ACL 提示)
Troubleshooting quick reference
For cross-platform symptoms, first check shared/faq.md。
| Symptom | Troubleshooting |
|---|---|
Bmob is undefined |
SDK not imported; or Node.js used the minified version (must use the source require('hydrogen-js-sdk/src/lib/app.js')) |
| Initialization reports 401 | Method A: Secret Key or API security code does not match the console; Method B: Application ID or REST API Key is wrong; or parameters from the two methods are mixed up (for example, passing the Application ID as the Secret Key) |
| Write succeeds but field value is not visible | Field name is misspelled (schemaless does not report an error); first get_project_tables compare |
| Query returns too little data | Default limit is 100 records; use query.limit(1000) or pagination |
set("id", ...) did not take effect |
When updating, you must use set("id", objectId)(not set("objectId", ...)) |
| Time range query is missing one record | Server time is in microsecond precision; add 1 second to the right end of the interval |
| Mini Program request failed | First check in the WeChat backend whether request valid domain has been added https://api.bmobcloud.com; if the SDK is imported via npm, you also need to run "Tools --> Build npm" in WeChat DevTools before compiling and running |
| Promise stays pending forever | A nonexistent method name was called (hydrogen does not throw an error, it just hangs); refer to Complete API |
| 9015 error | See bmob-error-codes 9015 topic |
Reference
- Complete API:BmobDocs/mds/data/wechat_app_new/index.md — cross-platform hydrogen-js-sdk main documentation
- Legacy API reference (still online):BmobDocs/mds/data/javascript/develop_doc.md
- SDK source code:https://github.com/bmob/hydrogen-js-sdk
- Error codes:
bmob-error-codes - MCP integration:
bmob-mcp