Created
January 7, 2019 18:40
-
-
Save williamsiuhang/7a3df7ffd60d8cf777e93935fe1b12b9 to your computer and use it in GitHub Desktop.
Basic mongo queries using Node.js / Express
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
// Connect | |
function connect() { | |
var mongoose = require('mongoose'); | |
mongoose | |
.connect('mongodb://user:[email protected]:1234/project', { | |
useNewUrlParser: true | |
}) | |
.then(() => { | |
console.log('MongoDB Connected'); | |
}) | |
.catch(err => { | |
console.log(err); | |
console.log('\x1b[31m\x1b[1m MongoDB Not Connected'); | |
}); | |
} | |
// Add document | |
function add_document() { | |
var Schema = mongoose.Schema, | |
ObjectId = Schema.ObjectId; | |
var ScaleSchema = mongoose.Schema({ | |
name: String, | |
price: Number, | |
quantity: Number | |
}); | |
// compile schema to model | |
var Scale = mongoose.model('Scale', ScaleSchema, 'music_scales'); | |
// a document instance | |
var scale1 = new Scale({ name: 'Introduction to Mongoose', price: 10, quantity: 25 }); | |
// save model to database | |
scale1.save(function (err, scale) { | |
if (err) return console.error(err); | |
console.log(scale.name + " saved to music_scale collection."); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment