【问题标题】:Need help creating mongoose query for special purposes需要帮助为特殊目的创建 mongoose 查询
【发布时间】:2015-12-31 16:51:49
【问题描述】:

我在某个 mongoose 查询中遇到了一些问题。

具有这样的架构的图像

var Task = new Schema({
           title: String,
           createdBy: {
                type: Schema.Types.ObjectId, ref: 'User'
           },
           pool: [{
                   userId: {type: Schema.Types.ObjectId, ref: 'User'},
                   accepted: {
                              type: Boolean,
                              default: false
                   }
           }]
        });

Task.find({pool: {$elemMatch:{userId: userId, accepted: false}}}, {'pool.$':1}).populate('createdBy', '_id name surname').populate('pool.userId', '_id name surname').exec(function(err, tasks){

所以现在问题是我真的只是得到了我想要的数组条目,但我没有得到文档的其余部分,比如标题和 createdBy。

任何人有任何建议如何解决这个问题?

亲切的问候托马斯

抱歉,我的架构中没有关键字 var。我急于提出我的问题。所以又来了。我正在使用 elemMatch 通过在数组中找到的标准来查找文档。它只返回找到的数组元素效果很好。我想要你的是它返回整个文档,如“标题和 createdBy 和池”,但在池中只有一个与 elemMatch 标准匹配的元素。

我希望我的问题现在更容易理解了。

诚挚的问候和感谢您的帮助

【问题讨论】:

    标签: javascript node.js express mongoose


    【解决方案1】:

    从title和createdBy中删除关键字var。

    原因:Schema 将 JavaScript 对象作为参数,在定义 javaScript 对象时,属性中不应使用 var。

    //This is correct
    {
      prop: "Something"
    }
    
    
    //This is not
    {
     var prop: "Something" 
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      相关资源
      最近更新 更多