簡體   English   中英

使用 mongoose 加入兩個集合並從兩個集合中獲取數據

[英]Join two collections using mongoose and get data from both

我有兩個集合用戶Taxdetails,我想從Taxdetails在兩個集合USER_ID joingin用戶和付款細節的姓名和電話號碼。

我正在這樣做:

User
    .find()
    .exec(function(err, userDetails) {
        if (err) {
            console.log("error in user collection");
            res
                .status(400)
                .json({ 'message':'error','success':false });
        } else {
            var userid = userDetails.map(function(obj) { 
                return obj._id;
              });
              Taxdetail
                  .find()
                  .exec({ user_id : { $in : userid } },function(err, requests) {
                        if(err){
                            console.log("error in TaxDetails collection");
                            res
                                .status(400)
                                .json({ 'message':'error','success':false });
                        }else{
                            console.log("Success, got some data");
                            res
                                .status(200)
                                .json(requests);
                        }                     
                    });
        }
    });

您可能需要在用戶架構中使用引用的架構,然后像這樣填充它:

var taxDetailSchema = new Schema({
    title: String
});

var taxDetail = mongoose.model('taxDetail', taxDetailSchema);

var userSchema = new Schema({
  name:  String,
  taxDetails: [{ type: Schema.Types.ObjectId, ref: 'taxDetail' }]
});

您的查詢如下所示:

User
.find()
.populate('taxDetails')
.exec(function(err, users) {

});

users應如下所示:

[
    {
        name: 'Some Name',
        taxDetails: [
            { title: 'Some Title' },
            { title: 'Some other Title' }
        ]
    }
]

貓鼬文檔在這里

希望能幫助到你

使用示例在 Mongoose 中加入兩個集合

簡單易用的填充

我們將使 Schema 成為用戶和另一篇文章,如下所示

const { Schema, model} = require("mongoose");

const UserSchema = new Schema({
   name:{
      type: String,
      required: true
   },
   email:{
      type: String,
      required: true
   },
   posts:[{
      type: Schema.Types.ObjectId, ref: "Post"
   }]
});


const PostSchema = new Schema({
   title: String,
   desc: String,
   User: {type: Schema.Tpes.ObjectId, ref: "User"}
});

export const Post = model("Post", PostSchema);
export const User = model("User", UserSchema);

然后

try {
   const user = User.create({
      name:"Robert Look",
      email: "phpcodingstuff@gmail.com"
   })

   try {
      const post1 = Post.create({
         title: "This is a first post",
         desc: "this a a first description"
         user: User._id // assign the _id from the user
      });
   } catch (err) {
      console.log(err.message)
   }
} catch (err) {
   console.log(err.message)
}

閱讀模型

User.findOne({
   name: "Robert Look"
}).populate('posts').exec((err, user) =>{
   if(err){
      console.log(err)
   }else{
      console.log(users.posts[0].desc)
   }
});

結論

我們在上面看到了如何使用 populate 我們還看到了如何在 mongoose (MongoDB) 中連接兩個文檔,如果您正確編寫查詢,那么您將獲得一個好的結果或您的 JSON。

更多信息: 貓鼬

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM