Mongodb查找(查询)返回空

时间:2017-12-01 18:54:31

标签: node.js mongodb express mongoose

拜托,我在这里做错了什么?我的搜索/查询全部返回空。我尝试了两种方法(注释掉其中一种方法)。

app.get('/dashboard', isLoggedIn, function(req, res) {
    //check if i still have logged in user in session
    console.log(req.user._id); //confirmed, I have it

    var owner = req.user._id; //assign user id to var owner

    //create a query
    var query = {createdby: owner};

    //first method using where clause  
    Election.find().where('createdby').equals(owner)
              .exec(function(err, elections) {
                    if (err) { return next(err); }
                    console.log(elections);
                    res.render("dashboard", { elections: elections });
            });

    //second method
    /**Election.find(query)
        .sort({ createdAt: "descending" })
        .exec(function(err, elections) {
            if (err) { return next(err); }

                console.log(elections);
                res.render("dashboard", { elections: elections });
            });**/

  //both methods returned empty

});

以下是模型,我无法从这里看到任何错误。有人应该帮助我,我已经在这几天了,谷歌没有帮助。

// models/election.js
// load the things we need
var mongoose = require('mongoose');


// define the schema for our election model
var electionSchema = mongoose.Schema({

local            : {
    title: String,
    disc: String,
    startdate: {type: String, required: true},
    enddate: {type: String, required: true},
    createdAt: {type: Date, default: Date.now()},
    updatedAt: {type: Date, default: Date.now()},
    createdby: {type: String},
    ballots: { 
        ballot: { type: String }
            }

}

});


  // create the model for elections and expose it to our app
  module.exports = mongoose.model('election', electionSchema);

2 个答案:

答案 0 :(得分:0)

我从未使用过可链接查询构建器API,因此我的响应包含不同的格式。但是,您可以尝试以下方法来查看querybuilder方法是否是原因。

另外,我会尝试将字符串owner转换为objectId:

var ownerObjectId = mongoose.Types.ObjectId(req.user._id)
Election.find({ createdby: ownerObjectId })
          .exec(function(err, elections) {
                if (err) { return next(err); }
                console.log(elections);
                res.render("dashboard", { elections: elections });
        });

答案 1 :(得分:0)

我终于弄明白了这个问题。我编辑了这一行:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    System.loadLibrary("opencv_java3");
    imv = (ImageView) findViewById(R.id.imageView);
}

public void cameera(View v) {
    Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(camera_intent, CAMERA_PIC_REQUEST);
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {

        Bitmap capturedImage = (Bitmap) data.getExtras().get("data");
        imv.setImageBitmap(capturedImage);

    }
}

全部谢谢