I am trying to make a method to fetch a "page" from the document base where the query matches _id
or permalink
.
The below code example returns a mongoose error:
'Cast to ObjectId failed for value "hello-world" at path "_id" for model "pages"'
Now, obviously the query isn't an ObjectId if the case is 'hello-world' or any other string permalink. So how do I go about using $or in this case, or is there a smarter way to go about it?
/**
* Describes methods to create, retrieve, update, and delete pages
* @returns void
*/
function Pages() {
this.pages = require('../models/pages')
this.users = require('../models/users')
require('mongoose').connect(require('../../config/database/mongodb').url)
}
/**
* Retrieve a page by permalink or id
* @param {string} pageQuery - id or permalink
* @callback {function} cFunction
*/
Pages.prototype.getOne = function(pageQuery, cFunction) {
this.pages.findOne({$or: [{ 'permalink': pageQuery }, { '_id': pageQuery }] })
.populate('author', 'email')
.select('title permalink body author')
.exec(function(error, result) {
if (error) {
cFunction(error)
return
}
cFunction(result)
})
}
via Brian Emilius
No comments:
Post a Comment