Skip to content

Instantly share code, notes, and snippets.

@lineus lineus/output.txt Secret
Created Jun 24, 2018

Embed
What would you like to do?
static method that removes refs from another collection
$: ./v0idifier.js
remaining b refs in a: 5b2fef2c50bbbc2b4dcc0eb1,5b2fef2c50bbbc2b4dcc0eb2
docs remaining in b: 2
$:
#!/usr/bin/env node
'use strict';
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
const conn = mongoose.connection;
const Schema = mongoose.Schema;
const schemaA = new Schema({
name: String,
b: [{
type: Schema.Types.ObjectId,
ref: 'b'
}]
});
const schemaB = new Schema({
val: String
});
schemaB.static('refRemove', function(doc) {
let cond = { b: { $elemMatch: { $eq: doc._id } } };
let upd8 = { $pull: { b: { $in: [doc._id] } } };
return Promise.all([
B.remove(doc),
A.update(cond, upd8).exec()
]);
});
const A = mongoose.model('a', schemaA);
const B = mongoose.model('b', schemaB);
const bees = [];
for (let i = 0; i < 3; i++) {
bees.push(new B({ val: `B${i}`}));
}
const a = new A({
name: 'A1',
b: bees.map((b) => b._id)
});
async function run() {
await conn.dropDatabase();
await a.save();
await B.create(bees);
await B.refRemove({ _id: bees[2]._id });
let found = await A.findOne({});
let count = await B.count();
console.log(`remaining b refs in a: ${found.b}`);
console.log(`docs remaining in b: ${count}`);
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.