繁体   English   中英

如何构造 PouchDB select 调用以返回存在字段且不是空字符串的所有项目

[英]How to construct a PouchDB select call to return all items where a field exists and is not an empty string

这是一个 PouchDB select 调用,它正确地返回 PouchDB 数据库中的所有文档,这些文档有一个名为“templateDetails”的字段和一个名为“areaName”的子字段,其中“areaName”的值为空字符串

selector: { 'templateDetails.areaName': ''}

如何更改此选择器以使其返回存在“templateDetails.areaName”且不是空字符串的所有文档?

只需使用$gt运算符(请参阅查询语言)。

例如,

selector: { "templateDetails.areaName": { $gt: "" } }

这是因为 Collation Specification,最好记录在这里

下面的片段演示了这种选择器的实际应用。 具有偶数编号 _id 的文档具有空字符串子字段值子字段为非空字符串、非字符串子字段或根本没有子字段。

 const gel = (id) => document.getElementById(id); const cel = (name) => document.createElement(name); // generate canned test documents function getDocsToInstall() { let docs = []; let i = 0; docs.push({ _id: i.toString(), field: null }); for (; i < 10; i++) { docs.push({ _id: i.toString(), field: { subfield: i % 2 === 0? "": i.toString() } }); } docs.push({ _id: (++i).toString(), field: { subfield: 9 } }); docs.push({ _id: (++i).toString(), field: { subfield: null } }); return docs; } let db; // init db instance async function initDb() { try { db = new PouchDB('test', { adapter: 'memory' }); await db.bulkDocs(getDocsToInstall()); } catch (err) { console.log(err.reason); } } function showDocs(tbodyId, docs) { const tbody = gel(tbodyId); docs.forEach(doc => { let el = cel("tr"); el.innerHTML = `<td>${doc._id}</td><td>${JSON.stringify(doc.field)}<td>`; tbody.appendChild(el); }); } initDb().then(async() => { // get all documents const alldocs = (await db.allDocs({ include_docs: true })).rows.map(row => row.doc); // display all document _id and field.subfield showDocs('alldocs', alldocs); // find documents where field.subfield have a non-empty text value. const result = await db.find({ selector: { "field.subfield": { $gt: "" } } }); // display all document _id and field.subfield showDocs('results', result.docs); });
 th, td { padding: .5em; text-align: left; min-width: 4em; } table { border-collapse: collapse; }
 <script src="//cdn.jsdelivr.net/npm/pouchdb@7.1.1/dist/pouchdb.min.js"></script> <script src="https://github.com/pouchdb/pouchdb/releases/download/7.1.1/pouchdb.memory.min.js"></script> <script src="https://github.com/pouchdb/pouchdb/releases/download/7.1.1/pouchdb.find.js"></script> <pre> <b>All Docs</b> <table> <tr><th>_id</th><th>field</th></tr> <tbody id="alldocs"></tbody> </table> </pre> <hr/> <pre> <b>Query: get all non-empty string subfields</b> { selector: { "field.subfield": { $gt: "" } } <table> <tr><th>_id</th><th>field</th></tr> <tbody id="results"></tbody> </table> </pre>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM