19-3-18 mongoose-连表查询populate用法

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属性,不返回其他属性。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Mongoose's `populate()` function is used to populate referenced fields in a document with actual data from another collection. It allows you to perform database joins in MongoDB. Let's say you have two models: `User` and `Post`. The `Post` model has a reference to the `User` model through a field called `author`. To use `populate()`, you would first define your models using Mongoose: ```javascript const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: String, age: Number, }); const postSchema = new mongoose.Schema({ title: String, content: String, author: { type: mongoose.Schema.Types.ObjectId, ref: 'User', }, }); const User = mongoose.model('User', userSchema); const Post = mongoose.model('Post', postSchema); ``` Now, let's say you want to find all posts and populate the `author` field with the actual user data. You can do that using the `populate()` function: ```javascript Post.find().populate('author').exec((err, posts) => { if (err) { console.error(err); return; } console.log(posts); }); ``` This will fetch all posts and populate the `author` field with the corresponding user data from the `User` collection. You can then access the populated data using dot notation, like `post.author.name`. You can also populate multiple fields by passing an array of field names to the `populate()` function, like `populate(['author', 'category'])`. It's important to note that populate is an expensive operation, as it involves multiple database queries. So, use it judiciously and consider using it only when necessary to avoid performance issues.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值