mongoose find by id code example

Example 1: mongo console find by id

db.collection.find({_id:ObjectId('5e208c18d598b806c869ca37')}).pretty()

Example 2: find one with specofoc id mongoose

YOUR_MODEL_NAME.findOne({_id: reqParameterID}, function(err, result) {
    if (err) {
      console.log(err);
    } else {
      // Do Something 
    }
  });

Example 3: mongoose response to object

MyModel.findOne().lean().exec(function(err, doc) {
    doc.addedProperty = 'foobar';
    res.json(doc);
});

Example 4: findbyid mongoose

// Find the adventure with the given `id`, or `null` if not found
await Adventure.findById(id).exec();

// using callback
Adventure.findById(id, function (err, adventure) {});

// select only the adventures name and length
await Adventure.findById(id, 'name length').exec();

Example 5: mongoose where

exports.generateList = function (req, res) {
    subcategories
            .find({})//grabs all subcategoris
            .where('categoryId').ne([])//filter out the ones that don't have a category
            .populate('categoryId')
            .where('active').equals(true)
            .where('display').equals(true)
            .where('categoryId.active').equals(true)
            .where('display').in('categoryId').equals(true)
            .exec(function (err, data) {
            if (err) {
                console.log(err);
                console.log('error returned');
                res.send(500, { error: 'Failed insert' });
            }

            if (!data) {
                res.send(403, { error: 'Authentication Failed' });
            }

            res.send(200, data);
            console.log('success generate List');
        });
    };

Example 6: callback mongoose get value from document

var query = Model.find({});

query.where('field', 5);
query.limit(5);
query.skip(100);

query.exec(function (err, docs) {
  // called when the `query.complete` or `query.error` are called
  // internally
});

Tags:

Go Example