如何在Mongodb中使用node.js加入集合?

yzuktlbb  于 2022-12-12  发布在  Go
关注(0)|答案(4)|浏览(151)

我正在使用node.js进行mongodb连接查询,我有两个集合,我想连接这两个集合并填充数据。
饮品系列

[{
  "_id": "580a2f7615a0161010a23bfg",
  "name": "Pepsi",
  "createDate": "2016-10-21T15:08:27.405Z"
 }, {
  "_id": "580a2f7615a0161010bge345",
  "name": "Mirinda",
  "createDate": "2016-10-21T15:08:27.405Z"
 }, {
  "_id": "580a2f7615a0161010vbgdt5",
  "name": "Coke",
  "createDate": "2016-10-21T15:08:27.405Z"
 }, {
  "_id": "580a2f7615a0161010vb9876",
  "name": "Thums Up",
  "createDate": "2016-10-21T15:08:27.405Z"
 }, {
  "_id": "580a2f7615a0161010vbgmnk9",
  "name": "Slice",
  "createDate": "2016-10-21T15:08:27.405Z"
}]

订单收集

[{
  "_id": "580fa9a92bb22e783b298798",
  "created_at": "2016-10-25T18:41:53.716Z",
  "tab": [{
      "created_at": "2016-10-26T00:21:33.100Z",
      "cost": 30,
      "quantity": 7,
      "name": "Mirinda"
 }]
 }, 
 {
   "_id": "580fa9a92bb22e783b29887h",
   "created_at": "2016-10-25T18:41:53.716Z",
   "tab": [{
       "created_at": "2016-10-26T00:21:33.100Z",
       "cost": 25,
       "quantity": 5,
       "name": "Pepsi"
    }]
}]

所以我想通过加入饮料系列来找到订单系列的名称。
订单架构

var mongoose = require("mongoose");

var OrderSchema = new mongoose.Schema({
   tab: [{
       quantity: Number,
       cost: Number,
       name: {
          type: String
       },
       created_at: {
          type: Date
       }
    }],
});
module.exports = mongoose.model("Order", OrderSchema);

饮料方案

var mongoose = require('mongoose'),
utilities = require('../config/utilities');

var DrinkSchema = mongoose.Schema( {
   drinks_name: { type: mongoose.Schema.Types.ObjectId, ref: 'Order'    },
   name: {
     type: String
   },
   id: {
     type: String
   },
   createDate: {
     type: String
   },
})
module.exports = mongoose.model("Drinks", DrinkSchema);

Node.js代码

var Drinks = require("../models/drinks"),
Orders = require("../models/orders"),
async = require('async'),
mongoose = require('mongoose');

exports.getOrdersList = function(req, res) {

   //How to Join Drinks and Orders Collection ?
   Drinks
   .find({})
   .populate('drinks_name', 'tab.name')
   .exec(function (err, result) { 
      console.log('The Drinks List is', result);
   });
}

请通过我的上述职位,让我知道,如果你有任何解决方案。

o2rvlv0m

o2rvlv0m1#

MongoDB是NoSQL数据库,所以你无法在MongoDB中进行连接。我的理解是,你想根据“Orders”的name字段从“Drinks”中检索数据。你可以做的是在Orders集合中找到每个文档的“tab.name”字段,然后在Drinks集合中找到它的“_id”字段。

Orders.find({"tab.name":"Mirinda"});
Drinks.find({"name":"Mirinda"}), { "_id" : 1", "created_at":1});

然后,您可以连接这两个结果,或多或少地得到您想要的。

voj3qocg

voj3qocg2#

看起来你的问题是错误的...你需要得到订单信息沿着项目,但项目名称应填充从饮料收集...
订单架构:

var mongoose = require("mongoose");
var ObjectId = mongoose.Schema.Types.ObjectId;

var OrderSchema = new mongoose.Schema({
   tab: [{
      itemId:{
        type: ObjectId,
        ref: 'Drinks',
        required: true
      },
       quantity: Number,
       cost: Number,
       created_at: {
          type: Date,
          default:Date.now
       }
    }],
     created_at: {
          type: Date,
          default:Date.now
       }

});
module.exports = mongoose.model("Order", OrderSchema);

饮料方案

var mongoose = require('mongoose');
var DrinkSchema = mongoose.Schema({
   drinks_name: { type: mongoose.Schema.Types.ObjectId, ref: 'Order'},
   name: {
     type: String
   },
   createDate: {
     type: Date,
     default: Date.now
   },
});
module.exports = mongoose.model("Drinks", DrinkSchema);

~
节点编码:

var Drinks = require("./drinks"),
Orders = require("./orders"),
mongoose = require('mongoose');
/* mongoose.connect('mongodb://connectionsrint'); */
   //How to Join Drinks and Orders Collection ?
   Orders
   .find({_id:'582ae63967190c92552f871b'})
   .populate('tab.itemId')
   .exec(function (err, result) {
    console.log(JSON.stringify(result));
   });

输出功率

[{"_id":"582ae63967190c92552f871b","__v":0,"created_at":"2016-11-15T10:40:57.256Z","tab":[{"itemId":{"_id":"582ae4988bd47efe54bc5282","name":"Pepsi","__v":0,"createDate":"2016-11-15T10:34:00.115Z"},"quantity":5,"cost":125,"_id":"582ae63967190c92552f871c","created_at":"2016-11-15T10:40:57.262Z"}]}]
erhoui1w

erhoui1w3#

MongoDB本身并不支持连接,但我们可以通过两种不同的方式实现连接方法:

  • 嵌入对象(在文档本身中嵌入引用对象)
  • 引用文档中引用对象的Storing _id。

如果已经使用mongoose ODM创建了一个模式,则可以使用
Drinks.find({}).populate('orders').exec(cb) .

下面是订单和饮料的模式中的一个小变化。您不需要成本字段,因为它可以基于每种饮料的数量进行计算。还可以找到填充查询。

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var Orders = new Schema({
    waiter: {type: String},
    table:  {type: Number},
    items: [
        {
            quantity: {type: Number, default: 1 },
            drink_id: {type: mongoose.Schema.Types.ObjectId, ref: 'Drinks'}
        }
    ],
    billed: false,
    timestamp : {
        createdAt: created_at,
        updatedAt: updated_at
    }
})

module.exports = mongoose.model('Order', Orders);

var Drink = new Schema({
    name: {type: String, required: true},
    cost: {type: Number, required: true}
    discount: { type: Number},
    timestamps: {
        createdAt: created_at,
        updatedAt: updated_at
    }
})

module.exports = mongoose.model('Drink', Drink);

============

For Querying : 

var Orders  = require('./Orders.js');

Orders.find({}).populate('drinks').exec(function(err, documents){
    // you will get drinks object in response 
})

如果订单中的特定数量被更新以反映在订单中,则必须编写一个查询来更新订单,并且可以使用聚合框架来计算特定表上的订单成本。

mrfwxfqh

mrfwxfqh4#

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("welcomedb");
  dbo.collection('orders').aggregate([
    { $lookup:
      {
        from: 'drinks',
        localField: 'tags.name',
        foreignField: '_id',
        as: 'orderdetails'
      }
    }
  ]).toArray(function(err, res) {
    if (err) throw err;
    console.log(JSON.stringify(res));
    db.close();
  });
});

相关问题