node.js Mongoose - 查询以从多个集合中获取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35795480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:01:02  来源:igfitidea点击:

Mongoose - query to get data from multiple collections

node.jsmongodbmongoose

提问by laxman

I want to get query of the mongoosein nodejs application as describe below out put.
user.js, comment.js and post.js are the model files I used.

我想在 nodejs 应用程序中查询猫鼬,如下所述。
user.js、comment.js 和 post.js 是我使用的模型文件。

user.js

用户.js

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

var userSchema = new Schema({  
        nick_name:{type:String},  
        email: {  
            type: String,  
            trim: true,  
            required: '{PATH} is required!',
            index: true,
        },     
    },{ collection: 'user'});

var User = mongoose.model('User', userSchema);
module.exports = User;  

comment.js

评论.js

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

var commentSchema = new Schema({  
         comment: type:String,  
         user_id:{
            type:Schema.Types.ObjectId, ref:'User'
         },  
         is_active :1
},{ collection: 'comment'});

post.js

post.js

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

var postSchema = new Schema({
        post: type:String,
        user_id:{
           type:Schema.Types.ObjectId, ref:'User'
        },
        is_active :1
},{ collection: 'post'});

wants to get out put as follows:

想出去如下:

{
 "nick_name":"prakash",
 "email":"[email protected]",
 "comments":[
      {
      "comment":"this is a comment text1",
      "is_active":1,
      },
      {
      "comment":"this is a comment text2",
      "is_active":1,
      }
 ],
 "posts":[
      {
      "post":"this is a post text1",
      "is_active":1,
      },
      {
      "post":"this is a post text2",
      "is_active":1,
      },
      {
      "post":"this is a post text3",
      "is_active":1,
      },
 ]
}

dependencies

依赖

"express"  => "version": "4.7.4",
"mongoose" => "version": "4.4.5",
"mongodb"  => "version": "2.4.9",
"OS"  => "ubuntu 14.04 lts 32bit",

if query is not possible ,please suggests me a proper mongoose plugn. but I don't want to any changes in user.js file and its userSchema object.

如果无法查询,请建议我一个合适的猫鼬插件。但我不想对 user.js 文件及其 userSchema 对象进行任何更改。

回答by PigBoT

There are no 'joins' in Mongo. But what you would do is change your User Schema to store the ObjectId's of the Comment and Post documents in an array of your User. Then use 'populate' when you need the data with the user.

Mongo 中没有“连接”。但是您要做的是更改您的用户架构以将 Comment 和 Post 文档的 ObjectId 存储在您的用户数组中。然后在需要用户的数据时使用“填充”。

const userSchema = new Schema({  
    nick_name:{type:String},  
    email: {  
        type: String,  
        trim: true,  
        required: '{PATH} is required!',
        index: true,
    },
    comments: [{ type: Schema.Types.ObjectId, ref:'Comment' }],
    posts: [{ type: Schema.Types.ObjectId, ref:'Post' }]
}, {timestamps: true});

mongoose.model('User', userSchema);

Your query would then look something like this:

您的查询将如下所示:

User.find()
    .populate('comments posts') // multiple path names in one requires mongoose >= 3.6
    .exec(function(err, usersDocuments) {
        // handle err
        // usersDocuments formatted as desired
    });

Mongoose populate docs

猫鼬填充文档

回答by Muthuramalingam Duraipandi

It is possible .you should use aggregation. it should work. Initiate the variable

这是可能的。你应该使用聚合。它应该工作。 启动变量

    var mongoose = require('mongoose');
    var userCollection = require('./user');//import user model file
    var resources = {
    nick_name: "$nick_name",
    email: "$email"};

    userCollection.aggregate([{
            $group: resources
        }, {
            $lookup: {
                from: "Comments", // collection to join
                localField: "_id",//field from the input documents
                foreignField: "user_id",//field from the documents of the "from" collection
                as: "comments"// output array field
            }
        }, {
            $lookup: {
                from: "Post", // from collection name
                localField: "_id",
                foreignField: "user_id",
                as: "posts"
            }
        }],function (error, data) {
         return res.json(data);
     //handle error case also
});

回答by fuelusumar

Of course it is possible, you just have to use populate, let me tell you how:

当然可以,你只需要使用populate,让我告诉你如何:

Import your schemas

导入您的架构

var mongoose = require('mongoose');
var userSch = require('userSchema');
var postSch = require('postSchema');
var commSch = require('commentSchema');

Init all the necessary vars

初始化所有必要的变量

var userModel = mongoose.model('User', userSch);
var postModel = mongoose.model('Post', postSch);
var commModel = mongoose.model('Comment', commSch);

And now, do the query

现在,做查询

postModel.find({}).populate('User')
    .exec(function (error, result) {
        return callback(null, null);
    });

commModel.find({}).populate('User')
    .exec(function (error, result) {
        return callback(null, null);
    }); 

This way you get the user inside of your comment and your post, to get the post and comments inside of your user, you have to do 3 queries, one for the user, one for the comments and one for the post, and mix all together

通过这种方式,您可以让用户进入您的评论和帖子,要获取用户内部的帖子和评论,您必须进行 3 个查询,一个针对用户,一个针对评论,一个针对帖子,然后混合所有一起