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

新手上路,请多包涵

我想 查询nodejs应用程序中的猫鼬,如下所述。

user.js、comment.js 和 post.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;

评论.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

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

想出去放如下:

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

依赖关系

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

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

原文由 laxman 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 460
1 个回答

Mongo 中没有“连接”。但是您要做的是更改您的用户架构以将评论和发布文档的 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);

您的查询将如下所示:

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

猫鼬填充文档

原文由 PigBoT 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏