MongoDB

mongoose

An mongodb object modeling for node.js

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

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Schema
const productSchema = new Schema({
    name: String,
    price: String,
});

mongoose.model("products", productSchema);

Get all documents in model

    const Products = mongoose.model("products", {name: String});
    
    Products.find(function (error, products) { // find() method
        if (err) return console.error(err);
        res.json(products);
    })

Add document with POST method

app.post('/add', (req, res) => {
    let newProduct = new Products(req.body); // new document instance
    newProduct.save(function (err, product) { // save() method
        if (err) return console.error(err);
        // send response of all products
        Products.find(function (error, products) {
            res.json(products)
        })
    })
})

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.

var dbo = db.db("mydb");
dbo.collection("customers")
  .find({})
    .toArray(function(err, result) {
      if (err) throw err;
      console.log(result);
    });

$pull()

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

db.collection("example")
    .findOneAndUpdate(
        { _id: sourceId }, // select sourceId
        { $pull: { lists: { _id: listId } } } // remove listId from lists
    )

$push()

The $push 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.

db.collection("example").updateOne(
  { _id: sourceId },
  {
    $push: {
      lists: { $each: [list], $position: destinationIndex }
    }
  }
);

Last updated

Was this helpful?