在mongoose中映射和获取两个集合的数据
我有两个集合User
和Contact
。 用户将要求另一个用户进行联系,两个用户名将被存储在具有状态的联系人collections中。 我想在很多其他地方使用联系人和用户,所以写了不同的模型。
现在我想获取联系人对象的用户configuration文件,联系人对象应该有联系人的用户信息。
用户架构
var UserSchema = new mongoose.Schema({ name : { type:String, default: '', required:'Please fill name.', trim: true }, mobile : { type:String, required:'Please fill mobile', unique:true, trim:true }, contacts:[{ type: mongoose.Schema.ObjectId, ref: 'Contact' }] });
联系模式
var ContactSchema = new mongoose.Schema({ owner: { type: mongoose.Schema.ObjectId, ref: 'User' }, user: { type: mongoose.Schema.ObjectId, ref: 'User' }, status: { type:String, default:'pending' } });
configuration文件API
User .findById(req.body.user_id) .populate({ path: 'contacts', select: 'user', }) .exec(function(err, user){ if (err) return res.send(err); res.status(200).json({'message':'Profile found.','user':user}); });
这里的回应如下:
{ "message": "Profile found.", "user": { "_id": "563037f3fe2b69e40b05c451", "mobile": "32435345", "__v": 1, "contacts": [ { "_id": "56303f04f1b8524f0d03d9a7", "user": "563037bafe2b69e40b05c44e" } ], "name": "Lorem" } }
在contacts数组中,我需要连接用户的名称和移动字段以及id。 我怎样才能做到这一点? 或者在模式devise中还有其他更好的方法吗?
你应该尝试mongoose深度填充模块。
var UserSchema = new Schema({ name: String, mobile: String, contacts: [{type: mongoose.Schema.ObjectId, ref: 'Contact'}] }) var ContactSchema = new Schema({ owner: { type: mongoose.Schema.ObjectId, ref: 'User' }, user: { type: mongoose.Schema.ObjectId, ref: 'User' }, status: { type:String, default:'pending' } });
使用mongoose实例初始化模块:
var deepPopulate = require('mongoose-deep-populate')(mongoose); UserSchema.plugin(deepPopulate, options /* more on options below */);
现在你可以填充:
User .findById(req.body.user_id) .deepPopulate(users, 'contacts.user', function (err, _users) { // _posts is the same instance as posts and provided for convenience users.forEach(function (user) { // post.contacts and user.contacts.user are fully populated }); });