Skip to content

Instantly share code, notes, and snippets.

@williamsiuhang
Created January 7, 2019 18:40
Show Gist options
  • Save williamsiuhang/7a3df7ffd60d8cf777e93935fe1b12b9 to your computer and use it in GitHub Desktop.
Save williamsiuhang/7a3df7ffd60d8cf777e93935fe1b12b9 to your computer and use it in GitHub Desktop.
Basic mongo queries using Node.js / Express
// 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