Code Snippet - How to Find Items by ObjectId with Mongoose

2014/07/051 min read
bookmark this
Responsive image

Table of Contents

  1. Introduction
  2. Sample Code
  3. Conclusion

Introduction

This snippet shows how to get all records where the Ids contain a specific ObjectId using Mongoose.

Sample Code

var q= yourCollection.find({ Ids: mongoose.Types.ObjectId('539ba44481973asdfe0c402bc6') });
    q.exec(function (err, items)
    {
        console.info(err);
        console.info(items.length);
    });

Conclusion

Using mongoose.Types.ObjectId() inside a find() query allows you to search for documents where an array field contains a specific ObjectId. This is useful when working with referenced documents in MongoDB.