如何从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对象的明确方法?
答案 0 :(得分:0)
问题出在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);
});
}