Mongoose – 查询从多个集合中获取数据
我想在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;
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'});
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",
如果查询是不可能的,请给我一个适当的mongooseplugn。 但我不想在user.js文件及其userSchema对象中进行任何更改。
Mongo没有“join”。 但是你要做的就是改变你的用户模式,将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);
你的查询会看起来像这样:
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填充文档
当然这是可能的,你只需要使用填充,让我告诉你如何:
导入您的模式
var mongoose = require('mongoose'); var userSch = require('userSchema'); var postSch = require('postSchema'); var commSch = require('commentSchema');
初始化所有必要的变数
var userModel = mongoose.model('User', userSch); var postModel = mongoose.model('Post', postSch); var commModel = mongoose.model('Comment', commSch);
现在,执行查询
postModel.find({}).populate('User') .exec(function (error, result) { return callback(null, null); }); commModel.find({}).populate('User') .exec(function (error, result) { return callback(null, null); });
通过这种方式,您可以在评论和post内部获得用户信息,以便获取用户的post和评论,您必须执行3个查询,一个用于用户,一个用于评论,另一个用于post,混合所有一起