You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
2.2 KiB
2.2 KiB
Mongo - Mongoose
Lesson Objectives
- Explain ODM
- Explain Schema
- Explain Create/Save
- Explain Find
- Explain Update
- Explain Remove
- Explain Helper Functions
Explain ODM
Explain Schema
article.js
var mongoose = require('mongoose');
mongoose.set('debug', true);
var Schema = mongoose.Schema;
var articleSchema = new Schema({
title: { type: String, required: true, unique: true },
author: { type: String, required: true },
body: String,
comments: [{ body: String, date: Date }],
date: { type: Date, default: Date.now },
hidden: Boolean,
meta: {
votes: Number,
favs: Number
}
});
//Creating an Article class -- will be stored in 'articles' collection
var Article = mongoose.model('Article', articleSchema);
module.exports = Article;
- String
- Number
- Date
- Boolean
- Mixed
- ObjectId
- Array
Explain Create/Save
var mongoose = require('mongoose');
var db = mongoose.connection;
var Article = require('./article.js');
//Setting up a new article
var newArticle = new Article({
title: 'Awesome Title',
author: 'Matt'
});
newArticle.hidden = false;
//connect to mongo
mongoose.connect('mongodb://localhost:27017/example');
//if the connection fails
db.on('error', function(){
console.log('error');
});
db.once('open', function() {
//we're connected!
//save article to the database
newArticle.save(function(err, article) {
if(err) {
console.log(err);
} else {
console.log(article);
}
mongoose.connection.close();
});
});
Explain Find
Article.find({author:'Matt'}, 'name -_id',function(err, articles){
console.log(articles);
mongoose.connection.close();
})
Explain Update
Article.update({ author: 'Matt' }, { $set : { author: 'Matthew' } }, { multi: true }, function (err, response) {...});
Explain Remove
Article.remove({author:'Matt'}, function(err){...});
Article.findOne({title:'Harry Potter'}, function(err, article){
article.remove();
});
Explain Helper Functions
- findById
- findOne
- findByIdAndUpdate
- findByIdAndRemove
- findOneAndUpdate
- findOneAndRemove