我在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 ] }
答案 0 :(得分: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
将允许您直接查询tickerIDSchema
。 findOne()
查询将如下所示显示,find()
应如下操作:
tickerList.find({}, function(err, data){
console.log(data)
})