Thursday, April 28, 2016

Node js mongoose partial string search

https://scotch.io/tutorials/using-mongoosejs-in-node-js-and-mongodb-applications

http://stackoverflow.com/questions/10156768/find-matching-partial-string

db.users.find({'name': {'$regex': 'sometext'}})
below example implementation showing search on partial first name
router.get('/merged_xxxxx/', function (req, res, next) {
  var conditions = {};
  var first_name  = req.query.first_name;
  var last_name  = req.query.last_name;
  var full_name  = req.query.full_name;

  if (first_name !== undefined){
    var firstExp = {};
    firstExp ['$regex'] = first_name;
    conditions['first_name'] = firstExp;
  }
  if (last_name !== undefined){
    conditions['last_name'] = last_name;
  }

  if (full_name !== undefined){
    conditions['full_name'] = full_name;
  }
  console.log(conditions);
  KMMergedAuthors.find(conditions)
    .sort(
      buildSortClause(req)
    )
    .limit(getRecordsReturned(req, 50))
    .exec()
    .then(function (allMergedAuthors) {
      res.json(allMergedAuthors);
    });
});

1 comment: