我正在尝试从文档库中获取"页面"的方法,其中查询匹配 _id
或 permalink
。
下面的代码示例返回猫鼬错误:
'cast to objectid失败了,因为" path" _id" _id"的值" hello-world" for Model" pages"'
现在,如果情况是" hello-world"或任何其他字符串永久链接,显然查询不是objectid。那么,我该如何使用$或在这种情况下,还是有更聪明的方法?
/**
* 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)
})
}
页面模型
const mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId,
pages = new Schema({
title: { type: String },
permalink: { type: String, unique: true },
body: { type: String },
author: { type: ObjectId, ref: 'users' },
createdAt: { type: Date },
revisedAt: { type: Date }
})
.index({
title: 'text',
permalink: 'text',
body: 'text'
})
module.exports = mongoose.model('pages', pages)
用户模型
const mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId,
users = new Schema({
email: { type: String, unique: true },
username: { type: String, unique: true },
password: { type: String },
createdAt: { type: Date }
})
.index({
email: 'text',
username: 'text'
})
module.exports = mongoose.model('users', users)
看起来好像运行new ObjectId(pageQuery)
并且不是有效的objectid,它会丢下错误告诉您(即错误:传递的参数必须是12个字节或一个单个字符串24个十六进制字符的字符串。(
说,我只会在Pages.prototype.getOne
的开头使用一个尝试/捕获块来尝试施放PageQueryoid变量,如果您到达渔获块,您知道这是因为PageQuery不是有效的objectID。p>使用此方法,您不再需要$或过滤器,而只需根据PageQuery是有效的ObjectID构建确切的过滤器即可。以下只是一个可能的示例,但是您可以更新它以满足您的需求:
Pages.prototype.getOne = function(pageQuery, cFunction) {
var ObjectId = require('mongoose').Types.ObjectId
var pageQueryOid
try {
pageQueryOid = new ObjectId(pageQuery)
} catch(err) {
console.log("pageQuery is not a valid ObjectId...")
}
var filter
if (pageQueryOid) {
filter = { '_id': pageQueryOid }
} else {
filter = { 'permalink': pageQuery }
}
this.pages.findOne(filter)
.populate('author', 'email')
.select('title permalink body author')
.exec(function(error, result) {
if (error) {
cFunction(error)
return
}
cFunction(result)
})
}