gpt4 book ai didi

node.js - 如何使用 mongodb Nodejs 驱动程序在 $lookup 中使用 ObjectId

转载 作者:太空宇宙 更新时间:2023-11-04 01:55:24 26 4
gpt4 key购买 nike

请帮我找到合适的解决方案

存储用户详细信息的集合app_users

{
_id: {
$oid: "abcd1235a6ad4a56dadasd"
},
user_name: "vikas Kandari",
user_dp: "ASDAD486412.jpg"
}

存储用户预订的集合预订

{
_id : {
$oid : "asdasdasdasdasd"
},
user_id : "abcd1235a6ad4a56dadasd",
booking_item : "some product",
booking_date : "datetime"
}

我使用的查找(左连接)查询是

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://root:root@localhost:3000/app';
const dbName = 'app';
MongoClient.connect(url, function(err, client) {
assert.equal(err, null);
console.log("Connected successfully to server");
const db = client.db(dbName);
const collection = db.collection('users');
collection.aggregate([{
$lookup: {
from: 'bookings',
localField: '_id',
foreignField: 'user_id',
as: 'bookings'
}
}]).toArray(function(err, docs) {
assert.equal(err, null);
console.log(docs);
});
client.close();
});

我想从用户集合中选择具有相应用户详细信息的预订,但它返回空白,因为 mongodb 正在将字符串与 objectId 进行比较,所以有什么方法可以执行此任务吗?

最佳答案

在查找之前添加此内容

$project:{
$let:
{
vars: { id:'_id.$oid' },
in: ObjectId("$$id")
}
}

更改为

$lookup: {
from: 'bookings',
localField: '_id.$oid',
foreignField: 'user_id',
as: 'bookings'
}

关于node.js - 如何使用 mongodb Nodejs 驱动程序在 $lookup 中使用 ObjectId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48187833/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com