MongoDB Node驱动v4.13如何加载不存在时不创建的集合?
MongoDB Node驱动v4.13+ 加载不存在时不自动创建集合的方法
在旧版本驱动中,我们可以通过db.collection()传入strict: true参数并配合回调,在集合不存在时触发错误:
db.collection('not_existing', { strict: true }, (err, res) => { if (err) { console.log('Collection does not exist'); } });
但v4.13版本移除了该函数的回调形式,且strict: true参数已不再生效——直接调用db.collection()即使集合不存在,也会生成对应的集合对象,甚至会在listCollections()的结果中出现该集合(属于逻辑存在,物理上未写入数据时不会占用空间,但不符合“不存在则不创建”的需求)。
要实现旧版本的效果,我们需要先主动检查集合是否存在,再决定是否获取,具体实现如下:
async function getCollectionStrict(db, collectionName) { // 查询目标集合是否存在,hasNext()会高效判断是否有匹配结果 const exists = await db.listCollections({ name: collectionName }) .hasNext(); if (!exists) { throw new Error(`Collection ${collectionName} does not exist`); // 也可根据需求返回null或执行自定义逻辑 } // 集合存在时返回对应的集合对象 return db.collection(collectionName); } // 使用示例 async function main() { try { const collection = await getCollectionStrict(db, 'not_existing'); // 集合存在时执行后续操作 } catch (err) { console.log(err.message); // 输出: Collection not_existing does not exist } }
补充说明
listCollections({ name: collectionName }).hasNext()的方式只会检查是否存在目标集合,不会返回全量集合列表,性能更优- 若集合不存在,可根据业务场景选择抛出错误、返回null或执行其他处理逻辑
- 这种写法完全替代了旧版本
strict: true的行为,确保只有当集合真实存在时才会获取对应的集合对象
内容的提问来源于stack exchange,提问作者user7996789
相关产品推荐
相关产品推荐

