mongoose query same field with different values

 ̄綄美尐妖づ 提交于 2021-02-18 09:54:28

问题


Is there a way to user mongoose.find({title:'some title'}) to query the same field with multiple values? For example something like this mongoose.find({title:'some title', title:'some other title'}) sends back only documents matching title:'some other title is there a way to accomplish this ?


回答1:


You should use the MongoDB $in operator -

mongoose.find({title: {$in: ['some title', 'some other title']}})

You provide an array to $in operator and it will return all the documents which have an exact title in the array specified.




回答2:


If you're building this off a URL query eg: http://url.com/posts?title=one but with multiple values in the query here's an approach:

Use a separator like & in your query like so http://url.com/posts?title=title&other%20title

Then setup your request function to operate with async:

eg. async function listPosts() {}

Then use the & seperator to detect if it's a query for multiple items or not and set your query accordingly. So the whole query for a list post would look something like this:

async function listPosts(req, res, next) {
  const urlParts = url.parse(req.url, true);
  const { query } = urlParts;
  // Check if URL query has & char and split into multiple query strings
  const multiQuery = async () => {
    // Return array of any query param values containing '&'
    const mQueryArr = Object.values(query).filter(i => i.indexOf('&') > -1);
    if (mQueryArr.length) {
      Object.keys(query).forEach((key) => {
        if (query[key].indexOf('&') > -1) {
          // Split strings containing '&' and set query to search multiple using
          // mongooses '$in' operator
          const queries = query[key].split('&');
          query[key] = { $in: queries };
        }
      });
    }
  };
  await multiQuery();
  Post.find(query)
    .exec((err, posts) => {
      if (err) {
        return next(err);
      }
      return res.json({ posts });
    });
}

Hope this helps someone as it took me a while to figure out the approach for a URL query with multiple queries for the same object key.




回答3:


The mongodb text search {"title":"some thing"} will return any document that has the word "some", or the word "thing" in it. I won't do an exact match to the phrase "some thing".

Therefore, if you wanted to find all titles that contained any series of words, you would just do {"title":"word one two three four something dog cat last word"} and it would return any document that has any of those words in it.

If you want to do exact phrase matching, then you would have to change your original query.



来源:https://stackoverflow.com/questions/43146716/mongoose-query-same-field-with-different-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!