Ir al contenido principal

Mongoose I

Mongoose


Mongoose is an ODM

  •  Object Data Model
Generate a schema to order the documents in MongoDB


Install

To install mongoose in your project, type:
  • npm install mongoose --save


Create a Model

All this code will be in a file <Model>.js to create a Model and be used as node package

// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// create a schema
var dishSchema = new Schema({
    name: {
        type: String,
        required: true,
        unique: true
    },
    description: {
        type: String,
        required: true
    }
}, 

//This part creates two date fields to store when a field is created and when is updated 

{
    timestamps: true
});

// the schema is useless so far

// we need to create a model using it

The model always will be in plural

var Dishes = mongoose.model('Dish', dishSchema);


// make this available to our Node applications
module.exports = Dishes;


Implementing the Model

First Approach

var mongoose = require('mongoose'),
    assert = require('assert');

var Dishes = require('./models/dishes-1');

// Connection URL
var url = 'mongodb://localhost:27017/conFusion';
mongoose.connect(url);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    // we're connected!
    console.log("Connected correctly to server");

    // create a new user
    var newDish = Dishes({
        name: 'Uthapizza',
        description: 'Test'
    });

    // save the user
    newDish.save(function (err) {
        if (err) throw err;
        console.log('Dish created!');

        // get all the users
        Dishes.find({}, function (err, dishes) {
            if (err) throw err;

            // object of all the users
            console.log(dishes);
                        db.collection('dishes').drop(function () {
                db.close();
            });
        });
    });
});

Second Approach

var mongoose = require('mongoose'),
    assert = require('assert');

var Dishes = require('./models/dishes-1');
// Connection URL
var url = 'mongodb://localhost:27017/conFusion';
mongoose.connect(url);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    // we're connected!
    console.log("Connected correctly to server");
    // create a new dish
    Dishes.create({
        name: 'Uthapizza',
        description: 'Test'
    }, function (err, dish) {
        if (err) throw err;
        console.log('Dish created!');
        console.log(dish);

        var id = dish._id;

        // get all the dishes
        setTimeout(function () {
            Dishes.findByIdAndUpdate(id, {
                    $set: {
                        description: 'Updated Test'
                    }
                }, {

//If value es true, the function will update the register and then back the object
//If false then the register will be back and then updated

                    new: true
                })
                .exec(function (err, dish) {
                    if (err) throw err;
                    console.log('Updated Dish!');
                    console.log(dish);

                    db.collection('dishes').drop(function () {
                        db.close();
                    });
                });
        }, 3000);
    });
});

Comentarios

Entradas populares de este blog

Android - Basic Steps (Service)

Service Run in the main thread of the hosting application Android can kill the Service if need the resources Purpose Supporting inter-application method execution Performing background processing Start a Service Call Context.startService(Intent intent)\ To call from a Fragment use getActivity().getApplicationContext().startService( intentService); Executing the service After call startService(...)  In the Service is executed the method onStartCommand(...) If the method returns the constant START_NOT_STICKY then Android will not restart the service automatically if the the process is killedp Foreground To execute the service foreground call the method startForeground() Use this if the user is aware of the process Bind to a Service Call the method Context.bindService( Intent service ServiceConnection con int flags ) Send Toast from the Service On the method onStartCommand receive the message   ...

Android - Basic Steps (Location & Maps)

Location Is composed by Latitude Longitude Time-stamp Accuracy Altitude Speed Bearing LocationProvider Types: Network  Wifi access points Cell phone towers GPS Passive Piggyback on the readings requested by other application Permissions Network  android.permission.ACCESS_COARSE_LOCATION android.permission.ACCESS_FINE_LOCATION GPS android.permission.ACCESS_FINE_LOCATION Passive Provider android.permission.ACCESS_FINE_LOCATION LocationManager System service for accessing location data getSystemService( Context.LOCATION_SERVICE ) Functions Determine the last known user location Register for location update Register to receive intents when the device nears or move away from a given geographic area LocationListener Defines callbacks methods that are called when Location or LocationProvider status change. Methods onLocationChanged(...) onProviderDisabled(...) onProviderEnabled(...) onStatusChan...

IIS - Permisions

IIS Permissions To enable the Active Directory connection in the IIS, follow the next steps: Go to IIS Go to Application Pool Select your App Pool Select Advanced Settings in the right side In the section Process Model Select in Identity value the property " NetworkService " You don´t need to restart your application