Skip to content

Instantly share code, notes, and snippets.

@lineus lineus/output.txt Secret
Last active Jun 8, 2018

Embed
What would you like to do?
you know, for kids - Orville Barnes
$: ./taco.js
a_other0
b_other0
c_other0
d_other0
e_other0
f_other0
g_other0
h_other0
i_other0
j_other0
k_other0
l_other0
m_other0
n_other0
o_other0
p_other0
q_other0
r_other0
s_other0
t_other0
u_other0
v_other0
w_other0
x_other0
y_other0
z_other0
$:
#!/usr/bin/env node
'use strict';
const _ = require('lodash');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
const conn = mongoose.connection;
const Schema = mongoose.Schema;
const otherSchema = new Schema({
val: String,
r: [{
type: Schema.Types.ObjectId,
ref: 'other'
}]
});
const schema = new Schema({
content: String,
other: {
type: Schema.Types.ObjectId,
ref: 'other'
}
});
const Other = mongoose.model('other', otherSchema);
const Test = mongoose.model('test', schema);
const others = [];
function createOthers(prefix, n) {
let pre = prefix || '';
let ret = [];
for (let i = 0; i < n; i++) {
let other = new Other({ val: `${pre}other${i}` });
ret.push(other.id);
others.push(other);
}
return ret;
}
createOthers(null, 1);
const alphabet = [
'a','b','c','d','e','f','g','h',
'i','j','k','l','m','n','o','p',
'q','r','s','t','u','v','w','x',
'y','z'
];
function add26Layers() {
let last;
alphabet.forEach((letter, index) => {
last = others[index];
let id = createOthers(letter + '_', 1)[0];
last.r.push(id);
});
}
add26Layers();
const test = new Test({
content: 'This is my content!',
other: others[0]._id
});
function makeRecursivePopObj(field, n) {
let ret = { path: field };
for (let i = 0; i < n; i++) {
let target = ret;
let bottom = false;
while(!bottom) {
if (!target.populate) {
bottom = true;
target.populate = {
path: field
};
} else {
target = target.populate;
}
}
}
return ret;
}
async function run() {
await conn.dropDatabase();
await Other.create(others);
await test.save();
const pop = makeRecursivePopObj('r', 26);
let found = await Test.findOne().populate({ path: 'other', populate: pop });
print(found);
return conn.close();
}
run();
function print(val) {
let path = val.other.r[0];
while(path) {
if (path.val) {
console.log(path.val);
path = path.r[0];
}
}
}
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.