Created
September 14, 2012 06:06
-
-
Save ishiduca/3720103 to your computer and use it in GitHub Desktop.
Searching embedded documents in MongoDB (mongoose)
This file contains hidden or 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
'use strict'; | |
module.exports = function (mongoose) { | |
mongoose = mongoose || require('mongoose'); | |
var note = { | |
type: String | |
, required: true | |
}; | |
var created = { | |
type: Date | |
, default: Date.now | |
}; | |
var CommentSchema = new mongoose.Schema({ | |
note: note | |
, created: created | |
}); | |
var NoteSchema = new mongoose.Schema({ | |
body: note | |
, created: created | |
, comments: [CommentSchema] | |
}); | |
var config = {}; | |
config.Note = mongoose.model('Note', NoteSchema); | |
config.mongo = { | |
server : 'mongodb://localhost:27017' | |
, db : 'zeroDev' | |
, mongodb: function () { | |
return [ this.server, this.db ].join('/'); | |
} | |
}; | |
return config; | |
}; | |
This file contains hidden or 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
'use strict'; | |
var mongoose = require('mongoose'); | |
var config = require('./config')( mongoose ); | |
var mongo = config.mongo; | |
var Note = config.Note; | |
var app = {}; | |
app.error = function (err) { | |
console.error(err); | |
return this; | |
}; | |
app.resResult = function (note, i) { | |
console.log('%d - %s', i, note.body.split(/\n/)[0]); | |
return this; | |
}; | |
app.search = function (cond) { | |
var that = this; | |
Note.find(cond, function (err, notes) { | |
console.log('cond: "%s"', JSON.stringify(Object.keys(cond))); | |
if (err) return that.error(err); | |
if (notes.length === 0) | |
return that.error('cond: "%s" not found', JSON.stringify(cond)); | |
notes.forEach(that.resResult.bind(that)); | |
console.log("------------------------------------------\n"); | |
}); | |
return this; | |
}; | |
mongoose.connect( mongo.mongodb() ); | |
console.log('[mongoose] MongoDB connected on "%s"', mongo.mongodb()); | |
app.search({body: /jquery/i }) | |
.search({'comments.note': /./ }) | |
.search({body: /p[^\s]+/i, 'comments.note': /./ }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment