node.js - 猫鼬填充两个简单的模式
问题描述
我坚持使用猫鼬populate()
方法。
这是我的模式:
const GroupSchema = Schema({
title: String,
ips: [
{
ip: String,
hostname: String,
added : { type : Date, default: Date.now }
}
]
});
module.exports = mongoose.model('groups', GroupSchema);
const UserSchema = Schema({
username: String,
ip: String,
groups: [
{
_id : { type: Schema.Types.ObjectId, ref: 'groups'},
added : { type : Date, default: Date.now }
}
]
});
module.exports = mongoose.model('users', UserSchema);
我正在尝试加入users.groups[]._id
,groups._id
但绝对没有运气。
这是我尝试的方法:
User.find().
populate('groups').
exec(function (err, user) {
if (err) return handleError(err);
console.log(user);
});
得到这个结果:
{ _id: 5b3e039a2f714d38ccf66cax,
username: 'rrrr',
ip: '10.1.1.1',
groups: [ [Object], [Object] ],
__v: 0 } ]
我想要这样:
{ _id: 5b3e039a2f714d38ccf66cax,
username: 'rrrr',
ip: '10.1.1.1',
groups: [{ title: sssss, added: ssss }, {title: xxxx, added: ssss}] ],
__v: 0 } ]
解决方案
您可以尝试使用$lookup
聚合
如果您使用的是 mongodb 3.4及以下版本
User.aggregate([
{ "$unwind": "$groups" },
{ "$lookup": {
"from": Groups.collection.name,
"let": { "groupId": "$groups._id" },
"pipeline": [
{ "$match": { "$expr": { "$eq": [ "$_id", "$$groupId" ] } } }
],
"as": "groups._id"
}},
{ "$unwind": "$groups._id" },
{ "$group": {
"_id": "$_id",
"username": { "$first": "$username" },
"ip": { "$first": "$ip" },
"groups": { "$push": "$groups" }
}}
])
如果您使用的是 mongodb 3.6及更高版本
User.aggregate([
{ "$unwind": "$groups" },
{ "$lookup": {
"from": Groups.collection.name,
"localField": "groups._id",
"foreignField": "_id",
"as": "groups._id"
}},
{ "$unwind": "$groups._id" },
{ "$group": {
"_id": "$_id",
"username": { "$first": "$username" },
"ip": { "$first": "$ip" },
"groups": { "$push": "$groups" }
}}
])
推荐阅读
- html - 父 div 与子 div 一起显示
- swift - 用于在字符串中查找日期的快速正则表达式
- excel - Excel:与电子邮件地址对应的自动电子邮件表行
- java - 强制对 Java 中的非线程安全消费者进行顺序评估
- android - 改造首次服务响应缓慢
- javascript - 使用optimize.google中的JS按类更改图像以进行A / B测试
- azure - 公开 Graylog Azure VM
- python - 如何使用 tkinter 编辑字典列表
- php - 从 PHP 执行 Puppeteer 时出错
- http - Elasticsearch 用于 POST 的 uri 的 http 方法不正确