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
Publicar un comentario