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

时间:2020-04-01 12:21:16

标签: javascript node.js database mongodb mongoose

我有两个模式模型。

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模型找到用户喜欢的两个猫列表。

1 个答案:

答案 0 :(得分:0)

您可以使用MongoDB中的$in查询来实现此目的。 此处的详细信息: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