Skip to content

Instantly share code, notes, and snippets.

@lineus lineus/output.txt Secret
Last active Sep 19, 2018

Embed
What would you like to do?
array of mixed docs with arbitrary keys - populating after generating dynamic populate paths
$: ./ratnesh3.js
All Assertions Pass.
$:
#!/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 productSchema = new Schema({
name: String
});
const schema = new Schema({
cartObjects: Array
});
const Product = mongoose.model('product', productSchema);
const Test = mongoose.model('test', schema);
const objs = [];
const products = '012345'.split('').map(n => {
let product = new Product({ name: `product${n}` });
let obj = {};
obj[`product${n}`] = { _id: product._id };
objs.push(obj);
return product;
});
const test1 = new Test({ cartObjects: objs.slice(0, 3) });
const test2 = new Test({ cartObjects: objs.slice(3, 6) });
async function run() {
await conn.dropDatabase();
await Product.create(products);
await Test.create([test1, test2]);
let docs = await Test.find({});
let paths = docs.map(doc => {
let keys = doc.cartObjects.map(e => Object.keys(e)[0]);
return {
doc: doc.id,
paths: keys.map(k => { return `cartObjects.${k}._id`; })
};
});
for (let doc of docs) {
let keys = doc.cartObjects.map(e => Object.keys(e)[0]);
let these = paths.find(o => o.doc === doc.id).paths.join(' ');
let popObj = { path: these, model: 'product', select: 'name -_id' };
let populated = await doc.populate(popObj).execPopulate();
let populatedNames = populated.cartObjects.map(o => {
let key = Object.keys(o)[0];
return o[key]._id.name;
});
assert.deepEqual(populatedNames, keys);
}
console.log('All Assertions Pass.');
return conn.close();
}
run();
@lineus

This comment has been minimized.

Copy link
Owner Author

commented Sep 19, 2018

Here's a version with comments if you like that sort of thing.

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.