Giter VIP home page Giter VIP logo

basic-mongo-nodejs's Introduction

Mongoose

Helps me to handle operations with mongoDB

definition

Schemas

Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.

Is possible to add values after creating a schema whit the method add

    const CamiloSchema = new Schema();
    CamiloSchema.add({ name: 'string', color: 'string', price: 'number' });

Models

Model is a class that's your primary tool for interacting with MongoDB. An instance of a Model is called a Document.

    ///////////////////////Module Name///Schema
    var myModel = mongoose.model("link", new mongoose.Schema({name: String}));

Methods

Documents have many of their own built-in instance methods. We may also define our own custom document instance methods too.

Custom Methods

Default Methods

Create Document

  • Example
  • Create: Model.create({data})
  • This function triggers the following middleware: save()

Finds Document

  • Examples
  • Find: Model.find({properties})
  • Model.findBy({properties}): Returns a fake promise, inorder to execute it is necessary add .exec()
  • Model.findById({properties}).exec(): Returns a promise
  • Model.findByIdAndUpdate({properties}, {dataToUpdate}, {new: true}).exec(): {new: true} it's necessary in order to return the new updated object, if not the retuned obj it's going to be the old one
  • Model.findOneAndRemove({properties})

Comparison Query Operators

Documentation

  • Match equal value

    • model.find({ property: {$eq: value }})
    • Docs
  • Select documents where the value is greater than (>)

    • Examples model.find({ property: {$gt: value }}), this property not work for getting data in base of the length (arrays)
    • Docs
  • Select documents where the value is greater or equal than (>=)

  • Matches any of the values specified in an array.

    • Examples model.find({ property: {$in: [value, value, ...] }})
    • Docs
  • Matches values that are less than a specified value.

  • Matches values that are less than or equal to a specified value.

  • Matches all values that are not equal to a specified value.

  • Matches none of the values specified in an array.

There are many other useful operators that can make our life easy, short list:

Update Operators

Documentation

  • Field: $inc, $min, $max, $mul, $rename, $set, $setOnInsert, $unset
  • Array Update Operators: $addToset, $pop, $pull, $push, $pullAll
    • Array Update Operator Modifiers: $each, $position, $slice, $sort

Aggregation Pipeline Stages

Some times is necessary to add new files on our document, limit the outcomes or group it, this is the Documentation

Cursor Operators

These methods modify the way that the underlying query is executed. Documentation

    model.find({ staff: {$in: ["d", "f"]} }).limit(2).exec();
    model.find({ staff: {$in: ["b", "c"]} }).sort("+students").exec();
    model.find({ staff: {$in: ["b", "c"]} }).sort("-students").exec();
    model.find({ staff: {$in: ["b", "c"]} }).sort({students: 1}).exec();
    model.find({ staff: {$in: ["b", "c"]} }).sort({students: -1}).exec();

###Query Helpers You can also add query helper functions, which are like instance methods but for mongoose queries. Query helper methods let you extend mongoose's chainable query builder API.

####Virtuals Virtuals are document properties that you can get and set but that do not get persisted to MongoDB. The getters are useful for formatting or combining fields, while setters are useful for de-composing a single value into multiple values for storage.

If you use toJSON() or toObject() mongoose will not include virtuals by default. This includes the output of calling JSON.stringify() on a Mongoose document, because JSON.stringify() calls toJSON(). Pass { virtuals: true } to either toObject() or toJSON().

  • Definition
  • Execution: every time we make a request through a Schema with a virtual definition that value is going to be returned by default

Documentation

Middleware

Middleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions.

Docs

Hooks

Compound index

Links

HTTP Status Codes

  • 200- OK; Standard response for successful HTTP requests
  • 201- Created; Request has been fulfilled. New resource created
  • 204- No Content; Request processed. No content returned
  • 301- Moved Permanently; This and all future requests directed to the given URI
  • 304- Not Modified; Resource has not been modified since last requested
  • 400- Bad Request; Request cannot be fulfilled due to bad syntax
  • 401- Unauthorized; Authentication is possible, but has failed
  • 403- Forbidden; Server refuses to respond to request
  • 404- Not Found; Requested resource could not be found
  • 500- Internal Server Error; Generic error message when server fails
  • 501- Not Implemented; Server does not recognize method or lacks ability to fulfill
  • 503- Service Unavailable; Server is currently unavailable

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.