我試圖提出一個方法從查詢匹配的文檔庫中獲取「頁面」_id
或permalink
。
下面的代碼示例返回一個錯誤貓鼬:
'Cast to ObjectId failed for value "hello-world" at path "_id" for model "pages"'
現在,很明顯的查詢是不是如果的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)
它看起來像'pageQuery'傳入的當前值是''hello-world「'。我想你是在調試一些東西,忘記在某處刪除一個變量聲明。因此錯誤。 –
@NeilLunn我在我的問題中爲頁面和用戶添加了模型。是的,我在測試中詢問'hello-world',但這就是關鍵所在。我希望能夠從ID OR永久鏈接匹配查詢的文檔庫中檢索頁面,該頁面可以是ID或永久鏈接。 –
是的,我收回,因爲你明確提供該字符串作爲這個函數的輸入。 *「搜索你的代碼,你知道這是真的」* –