如何在服务层使用Mongoose跳过和限制功能?

问题描述 投票:0回答:1

如何从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层中删除了排序,跳过和限制。你能告诉我如何在服务层使用这些吗?是否有一种将“data”数组转换为DocumentQuery对象的明确方法?

node.js mongodb mongoose dao service-layer
1个回答
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);
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.