find an object in array javascript mongoose code example

Example 1: mongoose find() example

// find all documents
await MyModel.find({});

// find all documents named john and at least 18
await MyModel.find({ name: 'john', age: { $gte: 18 } }).exec();

// executes, passing results to callback
MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});

// executes, name LIKE john and only selecting the "name" and "friends" fields
await MyModel.find({ name: /john/i }, 'name friends').exec();

// passing options
await MyModel.find({ name: /john/i }, null, { skip: 10 }).exec();

Example 2: 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 3: how to query array of object in mongoos

User.findOne({'local.rooms': {$elemMatch: {name: req.body.username}}}, function (err, user) {

        if (err){
            return done(err);
        }    

        if (user) {
            console.log("ROOM NAME FOUND");
            req.roomNameAlreadyInUse = true;
            next();

        } else {
            req.roomNameAlreadyInUse = false;
            console.log("ROOM NAME NOT FOUND");
            next();

        }

    });

Tags:

Go Example