我有这样的架构,并且想要获取给定userName和_id的用户对象:
{
"_id":ObjectId("5cb7267d7ea090083be865c6"),
"name": test,
"users":[
{
"userName": "user1",
"role": "admin"
},
{
"userName": "user2",
"role": "basic"
}]
},
{
"_id":ObjectId("5cb7267d7ea090083be865c7"),
"name": test,
"users":[
{
"userName": "user3",
"role": "admin"
},
{
"userName": "user4",
"role": "basic"
}]
}
我已经根据Mongo官方文档尝试了以下查询:
db.users.find( { _id: new ObjectId(5cb7267d7ea090083be865c6) },
{ users: { $elemMatch: { userName: 'user1' } } } )
我正在使用打字稿,并收到以下错误消息,但不确定如何继续:
Argument of type '{ users: { $elemMatch: { userName: string; }; }; }' is not assignable to parameter of type 'FindOneOptions'.
Object literal may only specify known properties, and 'users' does not exist in type 'FindOneOptions'.
答案 0 :(得分:0)
我认为您不小心添加了不必要的花括号,并以options argument的形式传递了{users: {...}}
。这就是为什么您的代码无法编译的原因。试试这个:
db.users.find( {
_id: new ObjectId(5cb7267d7ea090083be865c6),
users: { $elemMatch: { userName: 'user1' } }
});