【问题标题】:Get data from first collection and check if exist on second从第一个集合中获取数据并检查第二个集合是否存在
【发布时间】:2016-11-03 18:19:20
【问题描述】:

有问题:

用户时刻:

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 中设置的时刻以及一些用户 ID

【问题讨论】:

  • 你有多少数据?您需要多快的结果?
  • userMoments 集合中的momentId 引用moments 集合中的name

标签: node.js mongoose mongoose-schema


【解决方案1】:

为了实现这一点,我将提出以下示例:


算法

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

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


代码

       // 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(...)

【讨论】:

    猜你喜欢
    • 2017-03-11
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 2016-01-25
    • 1970-01-01
    • 2010-12-12
    • 1970-01-01
    相关资源
    最近更新 更多