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

时间:2016-11-15 06:15:50

标签: node.js mongodb collections

我正在使用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"
    }]
}]

所以我希望通过加入Drinks系列找到Order系列的名称。

订单架构

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

如果您有任何解决方案,请通过我的上述帖子告诉我。

3 个答案:

答案 0 :(得分:0)

你无法在MongoDB中创建Joins,因为它是NoSQL DB。我的理解是你想要从'饮料'中检索数据,具体取决于'订单'的名称字段。您可以做的是找到Orders集合中每个文档的'tab.name'字段,然后从Drinks集合中找到它的'_id'字段。

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

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

答案 1 :(得分:0)

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

  • 嵌入对象(在文档中嵌入参考对象)
  • 在参考文件中存储参考对象的_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 
})

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

答案 2 :(得分:0)

看起来你的问题是错的......你需要获得订单信息以及物品,但物品名称应该从饮品集中填充..

订单架构:

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"}]}]