Skip to content

Instantly share code, notes, and snippets.

@bennetthardwick
Created November 19, 2017 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bennetthardwick/a282c535fcc1b2532cbb0a18ede4f46a to your computer and use it in GitHub Desktop.
Save bennetthardwick/a282c535fcc1b2532cbb0a18ede4f46a to your computer and use it in GitHub Desktop.
Using a $text search with mongoose population
var express = require('express');
var server = express();
var mongoose = require('mongoose');
var async = require('async');
var db = mongoose.connect('localhost:27017/text');
var ChildSchema = new mongoose.Schema({
text: String
})
var ParentSchema = new mongoose.Schema({
name: String,
children: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Child' }]
})
ChildSchema.index({ '$**': 'text' });
var Child = mongoose.model('Child', ChildSchema);
var Parent = mongoose.model('Parent', ParentSchema);
var child_a = new Child({ text: "Hello world! I\'m alive!!" });
var child_b = new Child({ text: "Hello everyone! I\'m still alive!!" });
var child_c = new Child({ text: "Hello Mum! Do you love me?" });
var child_d = new Child({ text: "Okay. Goodbye cruel world!" });
var parent = new Parent({ name: "Sandra", children: [ child_a._id, child_b._id, child_c._id, child_d._id ] });
async.parallel([
cb => Child.remove({}).then(cb),
cb => Parent.remove({}).then(cb)
], () => {
async.parallel([
cb => child_a.save().then(cb),
cb => child_b.save().then(cb),
cb => child_c.save().then(cb),
cb => child_d.save().then(cb),
cb => parent.save().then(cb).catch((err) => console.log(err))
], () => {
Parent.find({})
.populate({
path: 'children',
match: { $text: { $search: "hello"}},
})
.exec()
.catch(err => console.log(err))
.then(doc => console.log(doc));
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment