Member-only story
Using MongoDB with Mongoose — Updating Data
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 =…