从第一个集合中获取数据并检查是否存在第二个集合

时间:2016-10-31 02:36:38

标签: node.js mongoose mongoose-schema

有问题:

userMoments:

userId: {
    type: String,
    required: true
},
momentId : {
    type : String,
    required : true
},
pay : {
    type : Number
},
momentActive : {
    type : Boolean,
    default : false
}

和时刻:

name: {
    type: String,
    required: true
},
img : {
    type : String
}

我需要从moments集合中获取所有不在集合userMoments中的内容以及一些userId

1 个答案:

答案 0 :(得分:0)

为实现这一点,我建议以下示例:

算法

(1)获取与momentId相关的userMoments存储的所有userId

(2)获取与我们获得的moments无关的所有momentId

代码

       // Get all momentId
       UserMoments.find({
              $in: arrayThatContainsUserIds,
           }, 'momentId')
           // Make every momentId unique
           .distinct('momentId')
           .exec()
           // get all moments that do not refer to ids we got before
           .then((ret) => find({
              $nin: Array.from(ret, x => x.momentId),
           }))
           .then((ret) => {
              // Here you have your moments
           })
           .catch(err => {});

之证件

$nin mongoDB documentation

distinct mongoose documentation

Array.from documentation

Promise documentation X.then(...).catch(...)