Created
November 19, 2017 10:10
-
-
Save bennetthardwick/a282c535fcc1b2532cbb0a18ede4f46a to your computer and use it in GitHub Desktop.
Using a $text search with mongoose population
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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