Member-only story

Using MongoDB with Mongoose — Queries

John Au-Yeung
3 min readJan 19, 2021

--

Photo by Matt Eason on Unsplash

To make MongoDB database manipulation easy, we can use the Mongoose NPM package to make working with MongoDB databases easier.

In this article, we’ll look at how to use Mongoose to manipulate our MongoDB database.

Queries

Mongoose comes with various query methods.

We can use the findOne method to return the first entry that matches the query.

For example, we can write:

async function run() {
const { createConnection, Schema } = require('mongoose');
const connection = createConnection('mongodb://localhost:27017/test');
const schema = new Schema({
name: {
first: String,
last: String
},
occupation: String
});
const Person = connection.model('Person', schema);
const person = new Person({
name: {
first: 'james',
last: 'smith'
},
occupation: 'waiter'
})
await person.save();
const p = await Person.findOne({ 'name.last': 'smith' }, 'name occupation');
console.log(p);
}
run();

We create the Person schema and save a document that’s created from the Person constructor.

Then we call findOne to find an entry.

The first argument is an object with the query. 'name.last' is the path to the nested field.

--

--

No responses yet