Created
May 22, 2015 19:56
-
-
Save jsumners/cbe6e521643742061568 to your computer and use it in GitHub Desktop.
A simple usage of Mongoose and its promise API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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