简体   繁体   English

如何使用MongoDB Node.js驱动程序在$ lookup中使用ObjectId

[英]How to use ObjectId in $lookup using mongodb nodejs drivers

Please help me to find out a suitable solution 请帮助我找到合适的解决方案

collection were users details are stored app_users 收集用户详细信息的集合app_users

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

collection where users bookings are stored bookings 用户预订存储预订的集合

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

Lookup(left Join) query i am using is 我正在使用的查找(左联接)查询是

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();
});

I want to select bookings with there corresponding user details from users collections but Its returning blank because mongodb is comparing string with objectId so is there any way to perform this task ? 我想从用户集合中选择具有相应用户详细信息的预订,但是由于mongodb正在将字符串与objectId进行比较,因此返回空白,是否有任何方法可以执行此任务?

Add This before the lookup 在查找之前添加此

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

Change to 改成

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM