【问题标题】:It is possible to pull elements from a referred objects' array using mongoose?是否可以使用 mongoose 从引用对象的数组中提取元素?
【发布时间】:2019-03-02 08:29:17
【问题描述】:

我有 2 个使用 ObjectId 与另一个相关的 mongo 模式:

var User = new Schema({
    username: {
      type:String,
      unique: true
    },
    password: { 
        type:String
    },
    verified:   {
        type: Boolean,
        default: false
    },
    lastActivity:{
      type:Date,
      default:Date.now
    }
});

还有一个watitingRoom 架构,其中列出了所有users

var WaitingRoom = new Schema({
    lastActivity:{
          type:Date,
          default:Date.now
    },
    clients: [{
        type : mongoose.Schema.ObjectId,
        ref: 'User'
    }],
    videocalls: [{
        type: mongoose.Schema.ObjectId,
        ref:'VideoCall'
    }]
});

所以,我想“刷新”我的clients 数组,拉取所有lastActivity 小于当前时间的客户端。我使用mongoose 中的$pull 工具进行了尝试。在谷歌搜索和混合不同的例子之后,我尝试了这样的事情:

WaitingRoom.findOneAndUpdate({}, { lastActivity: new Date(),
                                      $pull : {clients : {"clients.lastActivity": { $lt: new Date() }}}
                                     }, options)
    .populate("clients")
    .exec( function(error, waitingRoom) {
            if (err) { return res.status(500).send({ msg: err.message }); }

    })

找到唯一的等候室,更新lastActivity 字段并尝试拉出所有clients.lastActivity 小于当前日期的客户端。

(显然这段代码不起作用)

问题是我没有找到任何文档或示例来解释是否可以使用嵌套条件 clients.lastActivity 从引用的 ObjectId 架构中提取元素

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema mongoose-populate


    【解决方案1】:

    您需要首先从User 数据库中找到ID,然后需要从WaitingRoom 数据库中$pull 它们

    User.find({ lastActivity: new Date() }).then((users) => {
      const ids = []
      users.map((user) => {
        ids.push(user._id)
      })
      WaitingRoom.update({}, { $pull: { clients: ids }}, { multi: true }).then(() => {
        console.log('removed')
      })
    })
    

    【讨论】:

      猜你喜欢
      • 2020-06-02
      • 2019-04-23
      • 2011-10-11
      • 2017-04-18
      • 2022-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-10
      相关资源
      最近更新 更多