Skip to content

Instantly share code, notes, and snippets.

@lineus lineus/foureight84.js Secret
Created Jul 5, 2018

Embed
What would you like to do?
you can also use a static method to create your population options before calling populate
#!/usr/bin/env node
'use strict';
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true });
const conn = mongoose.connection;
const Schema = mongoose.Schema;
const yetAnotherSchema = new Schema({
name: String
});
const otherSchema = new Schema({
name: String
});
const schema = new Schema({
name: String,
other: {
type: Schema.Types.ObjectId,
ref: 'other'
},
another: {
type: Schema.Types.ObjectId,
ref: 'yetAnother'
}
});
schema.statics.conditionalPopulate = function(path) {
let pathsToPopulate;
if (path === 'other') {
pathsToPopulate = `${path} another`;
} else {
pathsToPopulate = path;
}
return this.findOne({}).populate(pathsToPopulate);
};
const YetAnother = mongoose.model('yetAnother', yetAnotherSchema);
const Other = mongoose.model('other', otherSchema);
const Test = mongoose.model('test', schema);
const yetAnother = new YetAnother({ name: 'yet another' });
const other = new Other({ name: 'some other'});
const test = new Test({
name: 'testing123',
other: other._id,
another: yetAnother._id
});
async function run() {
await conn.dropDatabase();
await yetAnother.save();
await other.save();
await test.save();
let found = await Test.conditionalPopulate('other');
console.log(found);
return conn.close();
}
run();
$: ./foureight84.js
{ _id: 5b3de302d6b8ad0f37ed3410,
name: 'testing123',
other: { _id: 5b3de302d6b8ad0f37ed340f, name: 'some other', __v: 0 },
another: { _id: 5b3de302d6b8ad0f37ed340e, name: 'yet another', __v: 0 },
__v: 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.