Professional Documents
Culture Documents
console.log(books);
});
findById is executed immediately and accepts
a callback function, instead of allowing for a
chain of functions.
Author.findById('59b31406beefa1082819e72f', function(err, author) {
if (err) throw err;
console.log(author);
});
Once an object has been returned, you can modify any of its
properties to update it.
Once you have made the necessary changes, you call the save
method, just like when you were creating the object.
Model.findOneAndUpdate({ name: 'borne' }, { name: 'jason bourne’
},callback)
Author.findById('59b31406beefa1082819e72f', function(err, author) {
if (err) throw err;
author.linkedin = 'https://www.linkedin.com/in/jamie-munro-
8064ba1a/';
author.save(function(err) {
if (err) throw err
console.log('Author updated successfully');
});
});
After the author is successfully retrieved, the linkedin property is set
and the save function is called.
Mongoose is able to detect that the linkedin property was changed,
and it will send an update statement to MongoDB on only the
properties that have been modified.
Mongoose also offers two additional functions that
make finding an object and saving it in a single
step.
findByIdAndUpdate and findOneAndUpdate
Author.findByIdAndUpdate('59b31406beefa1082819e72f',
{ linkedin: 'https://www.linkedin.com/in/jamie-munro-8064ba1a/'
},
function(err, author) {
if (err) throw err;
console.log(author);
});
Deleting
Models have static deleteOne() and deleteMany() functions for
removing all documents matching the given filter.
BUT
It is not in meanstack
var mysql = require('mysql');
var connection =
mysql.createConnection('mysql://user:secret@localhost:3306/dbname');
connection.connect(function(error) {
if (error) {
return console.error(error.message);}
console.log('successfully connected!');});
var insertSql = 'INSERT INTO Presidents (Name, Terms) VALUES' +
'(\'Bill Clinton\', 2),’ + '(\'George W Bush\', 2)';
connection.query(insertSql, function(error, results) {
if (error) {
connection.release();
return console.error(error.message);
}
var selectSql = 'SELECT * FROM Presidents';
connection.query(selectSql, function(error,
results) {
if (error) {
connection.release();
return console.error(error.message);
}
console.log('results of SELECT:');
console.log(JSON.stringify(results, null, 2));