最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - OR operator with query builder in mongoose.js - Stack Overflow

programmeradmin1浏览0评论

How do I do an 'OR' operator with query builder in Mongoose?

I tried something like this: Find a user by ID or Username but it didn't work.

User.findOne({})
      .where( '_id', 'username').equals(param)

How do I do an 'OR' operator with query builder in Mongoose?

I tried something like this: Find a user by ID or Username but it didn't work.

User.findOne({})
      .where( '_id', 'username').equals(param)
Share Improve this question asked Mar 28, 2017 at 9:33 MattMatt 6494 gold badges12 silver badges20 bronze badges 5
  • where is the or in that? can you write pseudocode of what you want to achieve? which version of Mongoose do you use? – boroboris Commented Mar 28, 2017 at 9:36
  • Well, @boroboris that is my question... how to do an OR in mongoose, I am using latest version of Mongoose – Matt Commented Mar 28, 2017 at 9:39
  • I wanted to ask about the specific or conditions you want to use. – boroboris Commented Mar 28, 2017 at 9:49
  • Oh sorry, I tried to pass an options inside the WHERE in this format '_id', 'username' – Matt Commented Mar 28, 2017 at 9:51
  • I've found the part of the answer here: stackoverflow./questions/7382207/… so you can check that out too – boroboris Commented Mar 28, 2017 at 9:55
Add a ment  | 

2 Answers 2

Reset to default 12

Try something along those lines:

User.findOne({
     $or:[ 
       {'condition_1':param}, {'condition_2':param} 
     ]},
     function(err,docs){
       if(!err) res.send(docs);
     }
  });

My solution

// Needed to user ObjectID parison
const { ObjectID } = require('mongodb'); 

// Check if param is a valid ID otherwise is Username
let id_or_username = ObjectID.isValid(id) ? '_id' : 'username';

// Find post by ID or Username
Home
  .findOne({})
  .where(id_or_shortid).equals(id)
  .exec(callback)  
发布评论

评论列表(0)

  1. 暂无评论