2017-08-17 216 views
0

我想使用下面的查詢搜索多個單詞。當我搜索「文件的角色:」我應該得到有所有文檔和使用sequelize搜索多個單詞uisng postgres和javascript

function searchDocuments(req, res) { 
    const limit = req.query.limit || 6, 
    offset = req.query.offset || 0, 
    queryString = req.query.q, 
    splitString = queryString.split(' '); 
    let querySearch = ''; 

    splitString.forEach((query, index, initial) => { 
    console.log(initial[index]); 
    }); 


    if (!queryString) { 
    return res.status(400).json({ 
     message: 'Invalid search input' 
    }); 
    } 
    if (req.decoded.roleId === 1) { 
    return Document.findAndCountAll({ 
    limit, 
     offset, 
     where: { 
     title: { 
      $iLike: `%${querySearch}%` 
     } 
     }, 
     include: [ 
     { 
      model: User, 
      attributes: ['userName', 'roleId'] 
     } 
     ] 
    }) 
    .then(({ rows: document, count }) => { 
     if (count === 0) { 
     return res.status(404).json({ 
      message: 'Search term does not match any document.' 
     }); 
     } 
     res.status(200).send({ 
     document, 
     pagination: pagination(count, limit, offset), 
     }); 
    }) 
    .catch(error => res.status(400).send(error)); 

我只是想執行做一個或任務用的關鍵字sequelize查詢中有角色的所有文檔中的所有文件標題

+0

你看看postgresql的全文搜索功能嗎? – Aparichith

+0

是的,我已經得到了一個修復 – Iakhator

回答

0

從頂部添加以下代碼:

const limit = req.query.limit || 6, 
    offset = req.query.offset || 0, 
    queryString = req.query.q.replace(/ +(?=)/g, ''), 
    searchQuery = []; 

    if (!queryString) { 
    return res.status(400).json({ 
     message: 'Invalid search input' 
    }); 
    } 

    if (req.decoded.roleId === 1) { 
    const splitString = queryString.trim().split(' '); 

    splitString.forEach((query) => { 
     const output = { $iLike: `%${query}%` }; 
     searchQuery.push(output); 
    }); 

然後添加下面的你在哪裏查詢searchQuery

 where: { 
     title: { 
      $or: searchQuery 
     } 
     }