Node.js mongoose填充了两个简单的模式
我一直使用mongooseNode.js mongoose填充了两个简单的模式,node.js,mongodb,mongoose,mongoose-schema,mongoose-populate,Node.js,Mongodb,Mongoose,Mongoose Schema,Mongoose Populate,我一直使用mongoosepopulate()方法 以下是我的模式: const GroupSchema = Schema({ title: String, ips: [ { ip: String, hostname: String, added : { type : Date, default: Date.now } } ] }); module.exports = mongoose.model('groups', GroupSchema)
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);
我正在尝试加入用户组[].\u id
和组。\u 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 } ]
您可以尝试使用聚合
如果您使用的是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" }
}}
])
您正在获取组:[[Object],[Object]]中的数据。。。尝试使用
用户[0]进行控制台。组或用户[0]。组[0]
不工作。我从您的控制台{u id:5b3e039a2f714d38ccf66cax,用户名:'rrrr',ip:'10.1.1.1',组:[[Object],[Object],[Object],\uuv:0}似乎您正在获得组。。。问题是什么?例如,用户[0]有两个组,但未填充:user.find()。填充(“组”)。exec(函数(err,user){if(err)return handleError(err);console.log(用户[0]。用户名);console.log(用户[0]。组[0]。主机名);console.log(用户[0]。组[1]。主机名);});我得到'未定义'好的,谢谢,我会尝试找出如何使用查找