Ottoman.js能否自动创建Couchbase集合及自适应索引?
Ottoman.js自动创建Couchbase集合与索引的方法
问题背景
使用Ottoman.js操作Couchbase时,定义模型后必须手动创建集合和索引才能执行插入、查询操作——比如插入数据会提示“集合不存在”,执行find查询会触发索引错误。希望能像MongoDB的Mongoose那样,自动完成集合与索引的创建。
解决方案
Ottoman.js本身提供了自动创建集合和索引的API,无需手动在控制台操作,具体实现如下:
1. 自动创建集合
完成数据库连接后,调用Ottoman的ensureCollections()方法,它会遍历所有已定义的模型,自动创建对应的Couchbase集合。
2. 自动创建索引
- Schema声明的索引:对于Schema中标记
unique: true的字段(比如示例里的username),调用ensureIndexes()方法即可自动生成对应的唯一索引。 - 自适应索引(Adaptive Index):通过Couchbase的N1QL语句创建,结合Ottoman的数据库连接对象执行语句即可。
完整代码示例
const { Ottoman, Schema, model } = require("ottoman"); // 初始化Ottoman连接 const ottoman = new Ottoman({ connectionString: "couchbase://localhost", bucketName: "your-bucket-name", username: "your-username", password: "your-password", }); // 定义User模型 const UserSchema = new Schema({ username: { type: String, required: true, unique: true } }, { timestamps: true }); const User = model('User', UserSchema); // 启动并自动完成集合、索引创建 async function start() { try { // 连接数据库 await ottoman.connect(); // 自动创建所有模型对应的集合 await ottoman.ensureCollections(); // 自动创建Schema中定义的索引(如unique索引) await ottoman.ensureIndexes(); // 为User集合创建自适应索引 const bucket = ottoman.bucket; const query = `CREATE PRIMARY INDEX ON \`${bucket.name}\`.\`_default\`.\`User\` USING GSI WITH { "adaptive_index": true }`; await bucket.query(query); console.log("集合与索引创建完成"); // 测试插入 const newUser = new User({ username:'HelloWorld' }); let result = await newUser.save(); console.log("插入结果:", result); // 测试查询 let users = await User.find({},{}); console.log("查询结果:", users); } catch (err) { console.error(err); } } start();
补充说明
ensureCollections()和ensureIndexes()只需在应用启动时执行一次,无需每次请求调用。- 若要为所有集合批量创建自适应索引,可遍历已定义的模型动态生成N1QL语句执行。
- 不同版本的Ottoman(如v3+)API细节可能略有差异,但自动创建集合、索引的核心能力均支持。
内容的提问来源于stack exchange,提问作者Paul Brink
相关产品推荐
相关产品推荐

