To make MongoDB database manipulation easy, we can use the Mongoose NPM package to make working with MongoDB databases easier.
In this article, we’ll look at how to use Mongoose to manipulate our MongoDB database.
Updating
We can update the first with the given key and value with the updateOne
method.
For example, we can write:
const mongoose = require('mongoose');
const connection = mongoose.createConnection('mongodb://localhost:27017/test');
const schema = new mongoose.Schema({ name: 'string', size: 'string' });
const Tank = connection.model('Tank', schema);
Tank.updateOne({ size: 'small' }, { name: 'small tank' }, (err) => {
if (err) {
return console.log(err);
}
});
The first argument is the query for the document.
The 2nd argument is the key-value pair we want to update the document with.
The 3rd argument is the callback that’s called after the operation is done.
Documents
Mongoose documents are one to one mapping to documents as stored in MongoDB.
Each document is an instance of its model.
For example, if we have:
const mongoose = require('mongoose');
const connection = mongoose.createConnection('mongodb://localhost:27017/test');
const schema = new mongoose.Schema({ name: 'string', size: 'string' });
const Tank = connection.model('Tank', schema);
const tank = new Tank({ name: 'big tank' });
console.log(tank instanceof Tank);
console.log(tank instanceof mongoose.Model);
console.log(tank instanceof mongoose.Document);
then we can see all the console logs are true
.
The tank
document is an instance of the Tank
constructor.
It’s also an instance of the Model
constructor and the Document
constructor.
Retrieving
When we retrieve a document with findOne
, it returns a promise that resolves to a document.
For example, if we have:
const { runInContext } = require('vm');
async function run() {
const mongoose = require('mongoose');
const connection = mongoose.createConnection('mongodb://localhost:27017/test');
const schema = new mongoose.Schema({ name: 'string', size: 'string' });
const Tank = connection.model('Tank', schema);
const tank = new Tank({ name: 'big tank' });
await tank.save();
const doc = await Tank.findOne();
console.log(doc instanceof Tank);
console.log(doc instanceof mongoose.Model);
console.log(doc instanceof mongoose.Document);
}
run();
We see again that all 3 console logs are true
, so we know that documents are retrieved with findOne
.
Updating
We can modify a document and call save
to update a document.
For example, we can write:
const { runInContext } = require('vm');
async function run() {
const mongoose = require('mongoose');
const connection = mongoose.createConnection('mongodb://localhost:27017/test');
const schema = new mongoose.Schema({ name: 'string', size: 'string' });
const Tank = connection.model('Tank', schema);
const tank = new Tank({ name: 'big tank' });
await tank.save();
const doc = await Tank.findOne();
doc.name = 'foo';
await doc.save();
}
run();
We get the document we want to change with the findOne
method.
Then we set the property to the given value and the call save
to save the changes.
If the document with the given _id
isn’t found, then we’ll get a DocumentNotFoundError
raised:
const { runInContext } = require('vm');
async function run() {
const mongoose = require('mongoose');
const connection = mongoose.createConnection('mongodb://localhost:27017/test');
const schema = new mongoose.Schema({ name: 'string', size: 'string' });
const Tank = connection.model('Tank', schema);
const tank = new Tank({ name: 'big tank' });
tank.save();
const doc = await Tank.findOne();
try {
await Tank.deleteOne({ _id: doc._id });
doc.name = 'foo';
await doc.save();
} catch (error) {
console.log(error)
}
}
run();
We can also update all documents with the updateMany
method:
const { runInContext } = require('vm');
async function run() {
const mongoose = require('mongoose');
const connection = mongoose.createConnection('mongodb://localhost:27017/test');
const schema = new mongoose.Schema({ name: 'string', size: 'string' });
const Tank = connection.model('Tank', schema);
const tank = new Tank({ name: 'big tank' });
tank.save();
await Tank.updateMany({}, { $set: { name: 'foo' } });
}
run();
We update all documents in the tanks
collection by calling the updateMany
method with the 2nd argument being what we want to set.
This is indicated by the $set
property.
The first argument of updateMany
is the query object.
Conclusion
There are various ways to update MongoDB documents with Mongoose.