I want to findOne and findOneAndUpdate an element of a nested Array at a given index with the Node.js MongoDB driver.
Here is an example of that the data could look like:
{
"_id": "ObjectId('5d00e4ede5527164b6051797')",
"timestamp": 1560339693539,
"slices": [
{
"image": "/dev/shm/tmpBlecUn/S000008_P1.png",
"data": 123,
"force": 16012
},
{
"image": "/dev/shm/tmpBlecUn/S000009_P1.png",
"data": 345,
"force": 15989
},
{
"image": "/dev/shm/tmpBlecUn/S000010_P1.png",
"data": 567,
"force": 15870
}
]
}
Now for example, I want to get or update the value of "force" in the "slices" array at a specific index position.
I can't seem to find the right query or method for doing this. I've got a shabby solution to get the right element, but the "data" field normally has lots of data and I don't want to always get the whole slices array (>10mb).
This is my garbage solution for getting the force value:
function get_IdPrintLayerForce(_id, layer, callback) {
MongoClient.connect(conf.dbURL, {useNewUrlParser: true},
function(err, client) {
if (err) log.error(err);
const db = client.db(conf.dbName);
const collection = db.collection('print');
collection.findOne({_id: id}, {projection: {slices: true}},
function(err, res) {
if (err) log.error(err);
client.close();
const force = res['slices'][layer-1];
log.silly('Fetched specific layer force from print: ' + force);
callback(force, err);
});
});
}