Mongoose populate()未按要求工作



我有一个PaymentCard和一个User架构,并且希望在创建新的PaymentCard记录时定义现有用户的ID,以将特定卡链接到特定客户。它确实使用客户的mongoID创建了PaymentCard文档,但使用.populate((进行查询不会返回任何用户的任何卡,并返回所有用户的空数组。

为了能够从用户那里填充卡,您需要在创建支付时将卡id推送到用户卡数组中。但我在你的addPayment中看不到这种逻辑。

此外,如前所述,您需要更正用户模式,对于用户模式中的卡,ref必须为"PaymentCard"。(对于支付卡,您需要更正客户对"Customer"的引用(

为了使事情变得简单,我将排除jwt.verify部分,并描述我的解决方案。

正如我已经说过的,您需要将创建的卡id保存到用户的卡阵列:

router.post("/addPayment", async (req, res) => {
try {
const result = await PaymentCard.create(req.body);
const customerId = req.body.owner;
const response = await Customer.findByIdAndUpdate(
customerId,
{
$push: { cards: result._id } //result._id has the value of newly created card
},
{ new: true }
);
res.send(response);
} catch (err) {
console.log(err);
res.status(500).send("Something went wrong");
}
});

假设您有一位没有任何卡的客户:

{
"cards": [],
"_id": "5e823f6f76322539e0fb1668",
"name": "John",
"surname": "Smith",
"customerStatus": "Regular",
"email": "john@test.com",
"phoneNo": "123123123",
"__v": 0
}

当我们在邮寄路线上添加一张卡时,这个客户会是这样的:

{
"cards": [
"5e82400776322539e0fb1669"
],
"_id": "5e823f6f76322539e0fb1668",
"name": "John",
"surname": "Smith",
"customerStatus": "Regular",
"email": "john@test.com",
"phoneNo": "123123123",
"__v": 0
}

添加的卡片文档为:

{
"owner": "5e823f6f76322539e0fb1668",
"nameOnCard": "John Smith",
"cardNumber":"1234123412341234",
"cardIssuer": "VISA",
"cvc": 123,
"exp": 202008
}

现在你可以这样填充用户的卡片:

router.get("/getAll", async (req, res) => {
try {
const customerId = "5e823f6f76322539e0fb1668";
const result = await Customer.findById(customerId).populate("cards");
res.send(result);
} catch (err) {
console.log(err);
res.status(500).send("Something went wrong");
}
});

这将给您以下结果:

{
"cards": [
{
"_id": "5e82400776322539e0fb1669",
"owner": "5e823f6f76322539e0fb1668",
"nameOnCard": "John Smith",
"cardNumber": "1234123412341234",
"cardIssuer": "VISA",
"cvc": 123,
"exp": 202008,
"__v": 0
}
],
"_id": "5e823f6f76322539e0fb1668",
"name": "John",
"surname": "Smith",
"customerStatus": "Regular",
"email": "john@test.com",
"phoneNo": "123123123",
"__v": 0
}
  1. ref应该指向模型,而不是底层集合,因此在本例中指向'PaymentCard'而不是'paymentcards'
  2. 由于您要使用无界1-N关系,因此可以使用mongoose虚拟属性来解决此问题

在您的Customer架构上:

const Customer = new Schema({
...
});

Customer.virtual('cards', {
ref: 'PaymentCard',
localField: '_id',
foreignField: 'owner',
justOne: false
});
module.exports = ...

然后您可以使用.populate('cards')来获取虚拟的内容

最新更新