试图在mongoose

时间:2016-06-02 21:02:33

标签: node.js mongodb mongoose

我试图在mongoose中使用$ in来查找记录。但它不适合我。我在mongo shell中有相同的查询它的工作但在mongoose它不是workinh 我的架构

{
      "_id": "574f1f979f44e7531786c80f",
      "name": "mySchool2",
      "branch": "karachi",
      "location": "Clifton ",
      "block": false,
      "created_at": 1464803223441,
      "updated_at": 1464803223441,
      "__v": 0,
      "classes": [
        "574f216afd487958cd69772a"
      ],
      "admin": [
        "574f20509f44e7531786c811",
        "57508a2a3a0a919c16ace3c0"
      ],
      "teacher": [
        "574f20f39f44e7531786c812",
        "575002b48188a3f821c2a66e",
        "57500bbaea09bc400d047bf6"
      ],
      "student": [
        "574f2d56590529c01a2a473b",
        "574f2e5842c5885b1b1729ab",
        "574f2ed542c5885b1b1729ae",
        "574f2f57555210991bf66e07",
        "574f2fcd087809b11bd8d5e4",
        "574f301d1f5025d61b7392b6",
        "574f30481d02afff1bb00c71",
        "574f30b01d02afff1bb00c74",
        "574f310038136b3d1cf31b96"
      ]
    }

我的mongose查询

app.services._chkAdminSchool = function(payload){
        var deferred = q.defer();
        School
            //.find({ teacher:{$in:['574f20f39f44e7531786c812']}})

            .find({_id : "574f1f979f44e7531786c80f",admin:{"$in":[Object("57508a2a3a0a919c16ace3c0")]}})
            //.select(filers)
            .exec(function(error, record) {
                if (error) {
                    deferred.reject({
                        status:404,
                        message: 'Error in API',
                        error: error
                    });
                } else {
                    if(record.length === 0){
                        deferred.reject({
                            message: 'Admin and school doesnot match',
                            data: record
                        });
                    }else{
                        deferred.resolve({
                            message: 'Successfully get Admin',
                            data: record
                        });
                    }

                }
            });
        return deferred.promise;
    }

记录是返回空数组。 在此先感谢您的帮助

2 个答案:

答案 0 :(得分:0)

您使用的查询对我来说很好并返回对象,请确保在Schema中定义管理字段,如下所示:

"admin": [{type: mongoose.Schema.ObjectId }]

避免admin数组对象为字符串。如果您将Object("57508a2a3a0a919c16ace3c0")"57508a2a3a0a919c16ace3c0"进行比较,它将返回空数组,检查并重播给我,谢谢。

答案 1 :(得分:0)

我不确定您如何定义学校架构,但如果您将id数组中的admin保存为字符串,则不需要在您的mongoose查询中更改为Object

School.find({
  _id: "574f1f979f44e7531786c80f",
  admin: {
    $in : ['57508a2a3a0a919c16ace3c0']
  }
}, functin (err, record) {
...
})