mongodb中连表查询很方便,mongoose中的populate可以很方便的实现
如下:我们有两个Model,User和File,User的avatar属性是关联着File的id:
const User = mongoose.Schema({
role: String, // 角色
name: String, // name
pass: String,
avatar: {type: ObjectId, ref: 'File'}, // avatar关联着File中的id -> file id
type: { type: String },
deleted: { type: Boolean, default: false },
create_time: { type: Number, default: getTime },
update_time: Number,
correlate: ObjectId
});
// File中有name,path等属性
var FileSchema = mongoose.Schema({
name : String, //名称
original_name : String,
path : String, //路径
size : Number,
type : String,
creator : {type: ObjectId, ref: 'Admin'},
deleted : {type: Boolean, default: false},
create_time : {type: Date, default: Date.now}
});
现在,这两张表是关联表,查询User的时候如何关联查询出File中的所有属性呢?
如下是一个查询接口的实现,根据user name查询出user和关联的File所有数据:
const User = mongoose.model('User');
const user = await User.findOne({name: args.name}).populate('avatar', {name: 1}).exec();
return {
code: code.success,
data: {
user: {
name: user.name,
role: user.role,
create_time: user.create_time,
_id: user._id,
avatar: user.avatar
}
}
};
返回数据如下:
{
"code": 1000,
"data": {
"user": {
"name": "zlx",
"create_time": 1552707102552,
"_id": "5c8c6e1e453a08c319b8ef5a",
"avatar": {
"_id": "5c8c6e7adcc817cd1956afd8",
"name": "1552707194739-3hgslxkl.jpeg",
"path": "/workspace/DESserver/api/uploads/1552707194739-3hgslxkl.jpeg",
"size": 138229,
"type": "image/jpeg",
"original_name": "451551230300_.pic_hd.jpg",
"__v": 0,
"create_time": "2019-03-16T03:33:14.742Z",
"deleted": false
}
}
}
}
可见,File通过连表查询populate查询出了File所有的数据。
populate函数还有其他参数:
populate('avatar', {name: 1})
表示只返回File的name属性,不返回其他属性。
网友评论