Mongoose ~ Document - rohit120582sharma/Documentation GitHub Wiki

Querying documents

1. Logical queries, Regular expression, Pagination, Counting etc.

async function getAuthors(){
    const pageSize = 10;
    const pageNumber = 2;
    try {
        const author = await Author
            .find({ biography: /.*host.*/i })
            .where('name.firstName').equals('Rohit')
            .where('tags').in(['vaporizing', 'talking'])
            .skip((pageNumber - 1) * pageSize)
            .limit(pageSize)
            .sort('name.firstName')
            .select('name biography profilePicture');
        console.log(author);
    } catch(err) {
        console.error(err);
    }
}

2. Querying association with populates

Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s).

async function getBookById() {
    const author = await new Author({
        name: {
            firstName: 'Rohit',
            lastName: 'Sharma'
        }
    });
    const book = await new Book({
        title: 'Hum log',
        author: author._id
    });
    const match = await Book.findById(book.id).populate('author');

    // Show book with author data
    console.log(match);
}


Defining methods for documents

1. Virtual

It is like getter/setter method. The field is not saved in database instead it is computed when used.

authorSchema
    .virtual('fullName')
    .get(function() {
        return `${this.name.firstName} ${this.name.lastName}`;
    });

2. Middlewares

// It will run before the validation
authorSchema.pre('validate', function() {
    console.log('Calls before validation...');
});

// It will run before saving the document in collection
// It will not run before the validation
authorSchema.pre('save', function() {
    console.log('Calls before save...');
});

// It will run after saving the document in collection
authorSchema.post('save', function() {
    console.log('Calls after save...');
});

3. Instance methods

Functions added to the methods property of a schema get compiled into the Model prototype and exposed on each document instance. But we still haven't saved anything to MongoDB. Each document can be saved to the database by calling its save method.

authorSchema.methods.fullName = function(){
    console.log(`Author's name: ${this.firstName} ${this.lastName}`);
}

var author1 = new Author({
    name: {
        firstName: 'Andy',
        lastName: 'Munero'
    }
});
author1.save((err, result) => {
    if (err) return console.error(err);
    author1.fullName();
});


⚠️ **GitHub.com Fallback** ⚠️