Mongoose.js:查找所有喜欢 Cat 帖子的用户

我有两个模式模型。


const catSchema = new mongoose.Schema({

  name: 'string',

  likes: [

    {

      type: mongoose.Schema.Types.ObjectId, 

      ref: 'User',

      require: true

    }

  ],

});


const userSchema = new mongoose.Schema({

  email: {

    type: String,

    required: true,

    unique: true,

  },

});

假设 Cat 集合中有 10 个 Cat 文档。一位用户喜欢两个 Cat 文档。我想要做的是我想通过Cat模型找到用户喜欢的两个猫列表。


绝地无双
浏览 117回答 1
1回答

泛舟湖上清波郎朗

您可以使用$in来自 MongoDB 的查询来实现此目的。详细信息:https ://docs.mongodb.com/manual/reference/operator/query/in/从文档中: $in 运算符选择字段值等于指定数组中的任何值的文档。我曾经用它来获取用户所属的组。在您的情况下,您应该成功完成以下操作:const Cat = require('./models/Cat');Cat.find({ likes : { $in : [user] }}).exec((cats) => {  console.log(cats);});// user in this case should be the user document// the query checks if the user is included in the 'likes' arrady
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript