Mongoose find和findOne返回整个集合

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

我在javascript中有以下代码,数据库已经填充。现在,当我使用find()findOne()时,Mongoose会返回超过6000个条目的整个集合。为什么过滤器没有发生?

var tickerIDSchema = new mongoose.Schema({
  ticker: String,
  name: String,
  exchange: String,
  "_id": false
});

var tickerListSchema = new mongoose.Schema({
  complete: [tickerIDSchema]
});

tickerListSchema.index(
  { "complete.ticker": 1, "complete.exhcange": 1 },
  { unique: true }
);

var tickerList = mongoose.model("tickerList", tickerListSchema);


tickerList.findOne({"complete.ticker": "BMO"}, function(err, data){

  console.log(data)
})

结果:

{ _id: 5a44452bb1dac235f039c66c,
  __v: 0,
  complete:
   [ { ticker: 'AAPL', name: 'Apple Inc.', exchange: 'Nasdaq' },
     { exchange: 'Amex',
       name: 'Altisource Asset Management Corp',
       ticker: 'AAMC' },
     { exchange: 'Amex',
       name: 'Almaden Minerals, Ltd.',
       ticker: 'AAU' },
     { exchange: 'Amex',
       name: 'Aberdeen Emerging Markets Smaller Company Opportunities Fund I',
       ticker: 'ABE' },
     { exchange: 'Amex',
       name: 'Acme United Corporation.',
       ticker: 'ACU' },
     { exchange: 'Amex', name: 'AeroCentury Corp.', ticker: 'ACY' },
     { exchange: 'Amex',
       name: 'Adams Resources & Energy, Inc.',
       ticker: 'AE' },
     { exchange: 'Amex', name: 'Ashford Inc.', ticker: 'AINC' },
     { exchange: 'Amex',
       name: 'Air Industries Group',
       ticker: 'AIRI' },
     ... 6675 more items ] }
javascript mongodb mongoose
1个回答
1
投票

您似乎有一个额外的抽象层,这是不必要的。

此代码有效地创建具有单个属性的文档。

var tickerListSchema = new mongoose.Schema({
  complete: [tickerIDSchema]
});

结果是,您的mongodb集合tickerList中有一个文档,其中包含该单个属性complete中的所有数据。根据mongodb文档(https://docs.mongodb.com/manual/reference/method/db.collection.findOne/),findOne应该返回匹配的文档。因为您要查询子文档,返回的结果是父文档,其中包含您在tickerIDSchema中的所有数据

为了达到理想的效果,你的猫鼬代码应该看起来像这样。

var tickerIDSchema = new mongoose.Schema({
  ticker: String,
  name: String,
  exchange: String,
  "_id": false
});

tickerIDSchema.index(
  { "ticker": 1, "exchange": 1 },
  { unique: true }
);

var tickerList = mongoose.model("tickerList", tickerIDSchema);

tickerList.findOne({"ticker": "BMO"}, function(err, data){
  console.log(data)
})

删除tickerListSchema将允许您直接查询tickerIDSchemafindOne()查询将如图所示,find()应按如下方式运行:

tickerList.find({}, function(err, data){
    console.log(data)
})
© www.soinside.com 2019 - 2024. All rights reserved.