Skip to content

Instantly share code, notes, and snippets.

@lineus lineus/output.txt Secret
Created Aug 28, 2018

Embed
What would you like to do?
example of updating a specific embedded doc in an array
$: ./ratnesh.js
document updated succesfully
$:
#!/usr/bin/env node
'use strict';
const assert = require('assert');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true });
const conn = mongoose.connection;
const Schema = mongoose.Schema;
const schema = new Schema({
arr: Array
});
const Test = mongoose.model('test', schema);
const test = new Test({
arr: [
{
somepathA: {
_id: mongoose.Types.ObjectId(),
abc: 123,
xzy: 123
}
},
{
somepathB: {
_id: mongoose.Types.ObjectId(),
abc: 456,
xyz: 456
}
}
]
});
async function run() {
await conn.dropDatabase();
await test.save();
let query = { _id: test._id, 'arr.somepathA': { $exists: true } };
let update = {
$set: {
'arr.$.somepathA.abc': 'onetwothree'
}
};
await Test.updateOne(query, update);
let updated = await Test.findOne({});
assert.strictEqual(updated.arr[0].somepathA.abc, 'onetwothree');
console.log('document updated succesfully');
return conn.close();
}
run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.