如何从 DAO 获取文档列表并在服务层执行跳过、限制操作?
这是我的 DAO 函数。
function findAllPosts(first,second) {
return Post.find({});
}
这是我的服务层。
function findAllPosts(first, second) {
return new Promises((resolve, reject) => {
postDao.findAllPosts(Number(first), Number(second)).
then((data) => {
var sortingOrd = { 'createdAt': -1 };
resolve(data.sort(sortingOrd).skip(Number(first)).limit(Number(second)));
})
.catch((error) => {
reject(error);
});
});
}
我收到此错误。
TypeError: data.sort(...).skip is not a function
这是模型。
const mongoose = require('mongoose');
var timestamps = require('mongoose-timestamp');
var mexp = require('mongoose-elasticsearch-xp');
var updateIfCurrentPlugin = require('mongoose-update-if-current').updateIfCurrentPlugin;
var PostSchema = new mongoose.Schema({
title: String,
content: String,
categoryId: String,
location: String,
postSummary: String,
postImage: String,
userId: String,
author: String,
urlToImage: String,
newsSrc: String
});
PostSchema.plugin(mexp);
PostSchema.plugin(updateIfCurrentPlugin);
PostSchema.plugin(timestamps);
var Post = mongoose.model('Post', PostSchema);
Post
.esCreateMapping(
{
"analysis": {
"analyzer": {
"my_custom_analyzer": {
"type": "custom",
"tokenizer": "standard",
"char_filter": [
"html_strip"
],
"filter": [
"lowercase",
"asciifolding"
]
}
}
}
}
)
.then(function (mapping) {
// do neat things here
});
Post.on('es-bulk-sent', function () {
});
Post.on('es-bulk-data', function (doc) {
});
Post.on('es-bulk-error', function (err) {
});
Post
.esSynchronize()
.then(function () {
});
module.exports = Post;
我出于特定目的从 DAO 层中删除了排序、跳过和限制。你能告诉我如何在服务层使用这些吗?是否有将“数据”数组转换为 DocumentQuery 对象的显式方法?
问题出在 findAllPosts 函数内部。如果您需要跳过或限制,您应该在您的函数内部处理它们。
function findAllPosts(first,second, skip, limit) {
return Post.find({}).skip(skip).limit(limit);
}
或者完全删除 findAllPosts 函数并直接在主逻辑中使用 Post.find().limit().skip() 。
我的建议:实现一个独立的单一用途函数来返回你的响应:
function findAllPosts(query, options, cb) {
Post
.find(query)
.select(options.select)
.skip(options.skip)
.limit(options.limit)
.sort(options.sort)
.lean(options.lean)
.exec(function(err, docs {
if(err) return cb(err, null);
return cb(null, docs);
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句