Mongoose - 查询从多个集合中获取数据

lax*_*man 10 mongoose mongodb node.js

我想在nodejs应用程序中查询 mongoose,如下所述.
user.js,comment.js和post.js是模型文件.

user.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;  
Run Code Online (Sandbox Code Playgroud)

comment.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'});
Run Code Online (Sandbox Code Playgroud)

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'});
Run Code Online (Sandbox Code Playgroud)

想要出去如下

{
 "nick_name":"prakash",
 "email":"prakash@mailinator.com",
 "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,
      },
 ]
}
Run Code Online (Sandbox Code Playgroud)

依赖

"express"  => "version": "4.7.4",
"mongoose" => "version": "4.4.5",
"mongodb"  => "version": "2.4.9",
"OS"  => "ubuntu 14.04 lts 32bit",
Run Code Online (Sandbox Code Playgroud)

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

Pig*_*BoT 10

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);
Run Code Online (Sandbox Code Playgroud)

您的查询将看起来像这样:

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

Mongoose填充文档


小智 7

有可能。您应该使用aggregation。它应该工作。 初始化变量

    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
});
Run Code Online (Sandbox Code Playgroud)


fue*_*mar 1

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

导入您的架构

var mongoose = require('mongoose');
var userSch = require('userSchema');
var postSch = require('postSchema');
var commSch = require('commentSchema');
Run Code Online (Sandbox Code Playgroud)

初始化所有必要的变量

var userModel = mongoose.model('User', userSch);
var postModel = mongoose.model('Post', postSch);
var commModel = mongoose.model('Comment', commSch);
Run Code Online (Sandbox Code Playgroud)

现在,进行查询

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

commModel.find({}).populate('User')
    .exec(function (error, result) {
        return callback(null, null);
    }); 
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以将用户放入您的评论和帖子中,要获取用户中的帖子和评论,您必须执行 3 个查询,一个用于用户,一个用于评论,一个用于帖子,然后混合所有一起