我正在用node.js,express和mongoose创建一个api。我对mongosse很新,我想知道是否有更好的方法来做我想做的事。
我有两个集合:用户和费用。
用户示例:
{
"_id" : ObjectId("59c4bc6a39d9992d6407427e"),
"firstName" : "John",
"lastName" : "Doe",
"name" : "JohnD",
"password" : "xxxxx",
"__v" : 26,
"budget" : 400,
"saving" : 300,
"wage" : 1340,
"expenses" : [
ObjectId("59cd076544fa3e64ec32c7e3"),
ObjectId("59cd07f0ed7bd2192cab72bd"),
ObjectId("59cd0a78e19060451059dce7"),
ObjectId("59cd0b24e19060451059dce8"),
ObjectId("59cd0b8fe19060451059dce9"),
ObjectId("59cdf34be19060451059dcf4"),
ObjectId("59cdf3c1e19060451059dcf5"),
ObjectId("59cdf417e19060451059dcf6"),
ObjectId("59cdf446e19060451059dcf7"),
ObjectId("59cdf46ee19060451059dcf8"),
ObjectId("59cdf4bce19060451059dcf9"),
ObjectId("59cdf6dee19060451059dcfa"),
ObjectId("59cdf6f5e19060451059dcfb"),
ObjectId("59cdf768e19060451059dcfc"),
ObjectId("59cdf798e19060451059dcfd"),
ObjectId("59cdf806e19060451059dcfe")
]
}
费用示例:
{
"_id" : ObjectId("59cd07f0ed7bd2192cab72bd"),
"name" : "shopping",
"price" : 100,
"date" : 1506607687013,
"repetition" : 0,
"__v" : 0
}
{
"_id" : ObjectId("59cd0a78e19060451059dce7"),
"name" : "gazoil",
"price" : 50,
"date" : 1506607687013,
"repetition" : 0,
"__v" : 0
}
我想做一个带用户并返回所有费用的功能。我是否被迫遍历user.expenses中的所有objectId,或者有一种正确的方法直接使用mongoose?
答案 0 :(得分:3)
Mongoose有一种方法可以做你想做的事:Query Population
您需要设置正确的架构并将裁判推送给孩子,然后使用populate()
方法:
const user = await User
.findOne({ _id: 'yourObjId' })
.populate('expenses')
.exec()
console.log(user.stories)
答案 1 :(得分:0)