Skip to content

Instantly share code, notes, and snippets.

@jsumners
Created May 22, 2015 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsumners/cbe6e521643742061568 to your computer and use it in GitHub Desktop.
Save jsumners/cbe6e521643742061568 to your computer and use it in GitHub Desktop.
A simple usage of Mongoose and its promise API
'use strict';
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test2');
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function dbOpenCB(callback) {
console.log('open callback called');
});
const postSchema = mongoose.Schema({
title: String,
body: String,
author: {
name: String
}
});
const Post = mongoose.model('Post', postSchema);
const newPost = new Post({
title: 'foo',
body: 'bar',
author: {
name: 'Joe Blow'
}
});
const closeDB = db.close.bind(db);
newPost.save()
.then(function saveCB(newPost) {
console.log('newPost:');
console.dir(newPost);
})
.then(function() {
return Post.where('title', /^f/).exec();
})
.then(function findCB(posts) {
console.log('Posts:');
console.dir(posts);
})
.then(closeDB, closeDB)
.end();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment