This is where I keep my coding related notes-to-self. Help yourself!
var mongoose = require('mongoose');
1) create schema..
var UserSchema = new mongoose.Schema({schema-object})
sample_schema :
{
name: String
memberOn: {
type: Date,
default: Date.now()
},
location: Array,
activeToday: Boolean,
employer: {
type: Schema.ObjectId,
ref: 'Company'}
//EMBEDDED SUB DOCUMENT
bio: {
age: Number,
address: String,
heightInCms: Number,
nationality: String }
}
2) then export Schema as a ‘Model’
module.exports = mongoose.model('User', UserSchema)
1) install npm dependencies npm i –save mongoose body-parser express
2) require the relevant Model in the file that has functions that will use the Model
const User = require(./Models/User)
3) connect to DB
mongoose.connect(<DB URI string>)
Finding Items From DB
<Model>.find({}).exec((err, documents)=>{})
-> returns all ‘documents’ in the collection that bears the name of this Model
so User.find({}) will fetch all User documents from the ‘users’ collection that Mongoose automatically created when exporting the model.
<Model>.findOne({_id: 'XXXXX'}).exec((err, document)=>{})
This will need the body-parser
npm package to access the path variable that connotes the id of the document we want to receive. The path variable looks like this: example.com/path/:id. Accessing the :id
variable depends on what environment you’re in - for example, Lambda Functions makes these accessible in the events object that gets passed into the lambda function when invoked. If you’re using an express app then it will look like:
app.get('/path/:id', (req, res)=>{
let id = req.params.id
///use id in findOne()
})
Post an item to DB
setup for express
We need to use body-parser
to get JSON off the url.
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}));
use the Mongoose create method
The usual way of using this is with an established Schema. Let’s assume its a book schema with three fields : title, author and category. We then would have an express post route that creates a new Book object from the Schema, sets its properties/fields and saves. It looks like this:
app.post('/book', function(req, res) {
var newBook = new Book();
newBook.title = req.body.title;
newBook.author = req.body.author;
newBook.category = req.body.category;
newBook.save(function(err, book) {
if(err) {
res.send('error saving book');
} else {
console.log(book);
res.send(book);
}
});
});
NB: Note how the above does NOT use the Mongoose Create method?
Method 2 uses it, as below:
app.post('/book2', function(req, res) {
Book.create(req.body, function(err, book) {
if(err) {
res.send('error saving book');
} else {
console.log(book);
res.send(book);
}
});
});
Update with findOneAndUpdate() This Mongoose method takes 4 arguments
{_id: req.params.id}
{ $set: { title: req.body.title } }
{upsert: true}
See below:
app.put('/book/:id', function(req, res) {
Book.findOneAndUpdate({
_id: req.params.id
},
{ $set: { title: req.body.title }
}, {upsert: true}, function(err, newBook) {
if (err) {
res.send('error updating ');
} else {
console.log(newBook);
res.send(newBook);
}
});
});