Javascript 如何让findOne返回一个元素?
我有这样一个问题:Javascript 如何让findOne返回一个元素?,javascript,mongodb,mongoose,Javascript,Mongodb,Mongoose,我有这样一个问题: customers.findOne({name:'X','files.author':'c','files.name':'d'},{'files.$':1},function(err,data2){... { name:"X" files:[ {name:"b" author:"a"} {name:"d" author:"c"} ] } 我的数据如下: customers.findOne({
customers.findOne({name:'X','files.author':'c','files.name':'d'},{'files.$':1},function(err,data2){...
{
name:"X"
files:[
{name:"b"
author:"a"}
{name:"d"
author:"c"}
]
}
我的数据如下:
customers.findOne({name:'X','files.author':'c','files.name':'d'},{'files.$':1},function(err,data2){...
{
name:"X"
files:[
{name:"b"
author:"a"}
{name:"d"
author:"c"}
]
}
显然,如果我这样做
这将返回文件[0]
。我想要文件[1]
。我该怎么做?这段代码是否已经这样做了,因此,我的错误在别处
编辑:
显然,
如果我做{name:'X','files.name':'d','files.author':'c'}
它会工作的
如果我做{name:'X','files.author':'c','files.name':'d'}
它不会
我的模式也颠倒了。我做了一个编辑来反映这一点<代码>名称实际上是在上面定义的
作者
。因此,在使用Mongoose的findOne
?时,我必须根据模式按顺序查询内容,尝试使用find
。它返回游标,以便您可以对其使用skip
和limit
方法:
customers.find({...}).skip(1).limit(1);
显然,我需要翻转查询并按模式中定义的顺序搜索内容。如果要匹配同一数组元素中的多个字段,则需要使用,而不是单独列出它们:
customers.findOne(
{name: 'X', files: {$elemMatch: {author: 'c', name: 'd'}}},
{'files.$':1},
function(err, data2) {...
当按当前的方式单独列出时,它们可以分别匹配不同的
文件数组元素。这是mongoose还是mongodb?你能链接到文档吗?它是mongo,所有的驱动程序都支持它:和。我强制执行文件。name
是唯一的,因此author
可以匹配多个,而name
只能匹配一个。考虑到这一点,它还能匹配不同的文件数组元素吗?@Houseman当然。如果不使用$elemMatch
,查询将匹配没有一个文件
元素同时匹配作者
和名称
,但有一个元素匹配作者
,另一个元素匹配名称
。