繁体   English   中英

MongoDB Find(查询)返回空

[英]Mongodb find(query) returning empty

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

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);

我从未使用过可链接查询构建器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 });
        });

我终于弄清楚了这个问题。 我编辑了这一行:

  //i changed this line Elections.find({ createdby: ownerObjectId }) //to this Elections.find({ 'local.createdby': ownerObjectId }) 

谢谢大家

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM