猫鼬 / MEAN.js - model.find() 如果过滤,则返回空数组

mongoose / MEAN.js - model.find() returns empty array if filtered

本文关键字:过滤 如果 返回 数组 MEAN js find model 猫鼬      更新时间:2023-09-26

>im 新的意思是.js所以它可能只是错误的语法,但是当我使用 model.find(( 和内部查询时(option.find({poll_id:1}(,它会返回一个空数组。

poll.server.model.js

'use strict';
/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    Schema = mongoose.Schema;
/**
 * Poll Schema
 */
var PollSchema = new Schema({
    poll_id: {type:Number},
    user_id: {type:Number},
    poll_question: {type:String},
    poll_language: {type:String},
    poll_description: {type:String},
    poll_description_raw: {type:String},
    poll_weight_additional: {type:Number},
    poll_flag_active:{type:Number,default:1},
    poll_flag_18plus:{type:Number,default:0},
    poll_flag_expire:{type:Number,default:0},
    poll_flag_deleted:{type:Number,default:0},
    poll_flag_moderated:{type:Number,default:0},
    poll_flag_favourised:{type:Number,default:0},
    poll_date_expiration:{type:Date},
    poll_date_inserted:{type:Date,default:Date.now()},
    poll_flag_updated:{type:Date},
    show_thumbs:{type:Number},
    comments:{
        type: Schema.ObjectId,
        ref: 'User'
    }
});
mongoose.model('Poll', PollSchema);

选项.服务器.模型.js

'use strict';
/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    Schema = mongoose.Schema;
/**
 * Option Schema
 */
var OptionSchema = new Schema({
    option_id:{type:Number},
    poll_id:{type:Number},
    option:{type:Number}
});
mongoose.model('Option', OptionSchema);

polls.server.controller.js

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    errorHandler = require('./errors.server.controller'),
    Poll = mongoose.model('Poll'),
    Option = mongoose.model('Option'),
    _ = require('lodash');
/**
 * List of Polls
 */
exports.list = function(req, res) {
    Poll.find().limit(10).sort('_id')/*.populate('user', 'displayName')*/.exec(function(err, polls) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            for (var i=0; i < polls.length; i++) {
                // this works, returns an array with 10 items
                Option.find().exec(function(err,docs){
                    console.log(docs); 
                });
                // this doesnt! although i see in the former array that there are options
                // with the poll_id set to 1.
                Option.find({'poll_id':1}).exec(function(err,docs){
                    console.log(docs); 
                });
            }
            res.json(polls);
        }
    });
};

我做错了什么? 我查了一下,但我没有看到任何关于我问题的帖子。我尝试使用带有引号和不带引号的model.find((.where('poll_id'(.equals(1(,但没有引号。当我运行 model.find(( 时它可以工作,但无论我如何尝试过滤它,它都会返回一个空数组。谢谢你!

我知道

您是从 MySQL 导入的,但是使用 Mongoose 存储和搜索数据的正确方法是使用人口和参考:

var Polls = mongoose.Schema({
  options: [{ type: Schema.Types.ObjectId, ref: 'Options' }]
});
var Options = mongoose.Schema({
  ...
});
Polls
  .find()
  .limit(10)
  .sort('_id')
  .populate('options')
  .exec(function (err, polls) {
    console.log(polls.options); // => [ array of options ]
  });

相关文档可在此处找到 http://mongoosejs.com/docs/populate.html

强烈建议花一些时间重组数据,以便您可以使用人口和引用的许多优势(索引,更干净的代码等(。不要犯试图在文档存储上强制使用关系范例的错误。完全撕掉乐队助手或坚持你得到和知道的东西。

也就是说,您可以使用当前数据实现所需的内容,如下所示:

// npm install --save async
var async = require('async');
exports.list = function(req, res, next) {
  Poll.find().limit(10).sort('_id').exec(function (err, polls) {
    // In true HTTP parlance, the correct thing to do here would 
    // be to respond with a 500 instead of a 400. The error would
    // be coming from MongoDB, not a poorly formed request by the
    // client. Remember: 40Xs are for client errors and 50Xs are 
    // for server errors. If this is express, you should also look
    // into using a middleware error handler and passing the error 
    // down the line like so:
    if (err) return next(err);
    // Since you used a return statement above, there is no need for 
    // the if/else but this is a matter of style. If it helps with the
    // readability of your code, keep it. I choose to eliminate because
    // async code has enough nesting as it is!
    // https://github.com/caolan/async#maparr-iterator-callback
    async.map(polls, function (poll, callback) {
      // Now look up your option by its poll_id
      Option.find({'poll_id': poll.poll_id}, function (err, options) {
        if (err) return callback(err);
        poll.options = options;
        callback(null, poll);
      });
    }, function (err, data) {
      // Again, this would be a Mongo error, so pass it down the line to
      // handle as a generic 500.
      if (err) return next(err);
      // The data parameter is your newly mapped polls array
      res.json(data);
    });
  });
};    

请注意在没有人口和参考的情况下实现所需的更多样板。此外,在掩护下,人口只会击中 DB 两次,而在这里你击中它 11 次。从长远来看,您最好现在更改数据,然后产生关系/文档存储混合体。我见过他们,他们不是很;)

相关文章: