账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    mongoose 联表条件查询
    173
    0

    我有两张表ArticlesCategorys

    // Categorys表
    "use strict"
    
    const Mongoose = require('mongoose');
    const Schema = Mongoose.Schema;
    
    /**
     * [Category  分类]
     * title: 类名
     */
    const  Category = new Schema({
        title:  { type: String, required: true },
    },{
        versionKey: false,
        timestamps: true
    });
    
    module.exports = Mongoose.model('Categorys',Category);
    // Articles表
    "use strict"
    
    const Mongoose = require('mongoose');
    const Schema = Mongoose.Schema;
    
    /**
     * [articleSchema 文章模型]
     * params:{
     *     title : 标题
     *     body : 内容
     *     desc  :  描述
     *     category  :  分类
     *     tag  :      标签
     *     release_time: 发布时间
     *     reading : 阅读量
     * }
     */
    let  articleSchema = new Schema({
        title:  { type: String, required: true },
        body:   { type: String, required: true },
        desc:  { type:String },
        tag:   { type: Schema.Types.Mixed, required: true },
        category:   { type: Schema.Types.ObjectId,ref:'Categorys',required: true },//关联分类表
        release_time: { type: Date, default: Date },
        reading: { type:Number , default: 0 },
    },{
        versionKey: false,
        timestamps: true
    });
    
    module.exports = Mongoose.model('Articles',articleSchema);

    初始化后保存到数据库是酱紫的

    // Articles
    {
        "_id" : ObjectId("5e0876df9783c90c104eb531"),
        "reading" : 0,
        "title" : "这是A类的",
        "body" : "张占大号打不到",
        "tag" : "测试",
        "category" : ObjectId("5e0876c99783c90c104eb530"),
        "desc" : "张占大号打不到...",
        "release_time" : ISODate("2019-12-29T09:50:23.000Z"),
        "createdAt" : ISODate("2019-12-29T09:50:23.167Z"),
        "updatedAt" : ISODate("2019-12-29T09:50:23.167Z")
    },
    {
        "_id" : ObjectId("5e0876f89783c90c104eb532"),
        "reading" : 0,
        "title" : "这是B类的",
        "body" : "11111",
        "tag" : "测试",
        "category" : ObjectId("5e0876bf9783c90c104eb52e"),
        "desc" : "11111...",
        "release_time" : ISODate("2019-12-29T09:50:48.000Z"),
        "createdAt" : ISODate("2019-12-29T09:50:48.386Z"),
        "updatedAt" : ISODate("2019-12-29T09:50:48.386Z")
    }
    
    // Categorys
    {
        "_id" : ObjectId("5e0876c99783c90c104eb530"),
        "title" : "A类",
        "createdAt" : ISODate("2019-12-29T09:50:01.159Z"),
        "updatedAt" : ISODate("2019-12-29T09:50:01.159Z")
    },{
        "_id" : ObjectId("5e0876bf9783c90c104eb52e"),
        "title" : "B类",
        "createdAt" : ISODate("2019-12-29T09:49:51.022Z"),
        "updatedAt" : ISODate("2019-12-29T09:49:51.022Z")
    }
    

    下面这是我写的查询

    ArticleSchema.find().populate('category',['title','_id']).exec((err,docs)=>{
        console.log(docs);
    })
    
    // 结果
    [
        {
          "reading": 0,
          "_id": "5e0876df9783c90c104eb531",
          "title": "这是A类的",
          "body": "张占大号打不到",
          "tag": "测试",
          "category": {
            "_id": "5e0876c99783c90c104eb530",
            "title": "A类"
          },
          "desc": "张占大号打不到...",
          "release_time": "2019-12-29T09:50:23.000Z",
          "createdAt": "2019-12-29T09:50:23.167Z",
          "updatedAt": "2019-12-29T09:50:23.167Z"
        },
        {
          "reading": 0,
          "_id": "5e0876f89783c90c104eb532",
          "title": "这是B类的",
          "body": "11111",
          "tag": "测试",
          "category": {
            "_id": "5e0876bf9783c90c104eb52e",
            "title": "B类"
          },
          "desc": "11111...",
          "release_time": "2019-12-29T09:50:48.000Z",
          "createdAt": "2019-12-29T09:50:48.386Z",
          "updatedAt": "2019-12-29T09:50:48.386Z"
        }
      ]
    

    问题是我找出所以为A分类的文章,这样我因为怎么写查询呢,我在populate中加上match也不好使,会查出所有内容不满足match条件的category字段会为null。我想问问大家有没有什么方法能够实现呢?

    1
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 11 元积分
        全部回答
    • 0
    • 無奈年華、 普通会员 1楼

      在Mongoose中,联表查询通常通过populate方法实现。假设你有两个模型:User和Post,一个用户可以有多个帖子,那么它们的关联关系可能是这样的:

      ```javascript const userSchema = new mongoose.Schema({ name: String, posts: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Post' }] });

      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); ```

      如果你想根据某个条件查询用户的帖子,例如查询某个用户的所有标题包含特定关键词的帖子,你可以这样做:

      javascript User.findOne({ name: 'SomeUsername' }).populate({ path: 'posts', match: { title: new RegExp('someKeyword', 'i') } // 匹配标题包含someKeyword的帖子 }).exec((err, user) => { if (err) console.error(err); else console.log(user.posts); // 这里只会包含匹配条件的帖子 });

      在这个例子中,match选项就是我们在联表查询时添加的条件。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部