MongoDB

mongoose

An mongodbarrow-up-right object modeling for node.jsarrow-up-right

Connection

const mongoose = require('mongoose')
const Products = require('./models/products_model.js');
const db = mongoose.connection;

// Connecting to MongoDB
mongoose
    .connect('mongodb://localhost:27017/test', { useNewUrlParser: true, useUnifiedTopology: true })
    .catch(error => handleError(error));

db.on('error', err => {
    console.error(err);
});

db.once('open', function () {
    app.listen(port, () => console.log(`Server listening on port ${port}`));
});

Schema, Model

Get all documents in model

Add document with POST method

Methods

find()

To select data from a table in MongoDB, we can also use the find() method.

The find() method returns all occurrences in the selection.

The first parameter of the find() method is a query object. In this example we use an empty query object, which selects all documents in the collection.

$pull()

The $pullarrow-up-right operator removes from an existing array all instances of a value or values that match a specified condition.

$push()

The $pusharrow-up-right operator appends a specified value to an array.

Modifier:

  • $each: Appends multiple values to the array field.

  • $position: Specifies the location in the array at which to insert the new elements. Requires the use of the $each modifier. Without the $position modifier, the $push appends the elements to the end of the array.

Last updated