根据引用的objectid找到

时间:2016-01-27 11:09:43

标签: node.js mongodb mongoose

我有这个架构:

var scheme = schema({
    name: { type: String, required: true },
    deleted: { type: Boolean, default: false },
    user: {
        type: ObjectId,
        ref: 'User'
    },
    created: {type: Date, default: Date.now},
    modified: {type: Date, default: Date.now},
    eventinfo: { type: String, required: false },
    street: { type: String, required: false },
    city: { type: String, required: false },
    country: { type: String, required: false },
    postalcode: { type: String, required: false },
    usecurrentlocation: { type: Boolean, required: false },
    schedule_agenda_html: { type: String, required: false },
    gspsetup_html: { type: String, required: false },
    evdropboxstat: { type: Boolean, required: false },
    evsponsors_html: { type: String, required: false },
    evexhibitors_html: { type: String, required: false },
    floorplan_html: { type: String, required: false },
    social_media_fb: { type: String, required: false },
    social_media_tw: { type: String, required: false },
    social_media_li: { type: String, required: false },
    evorganizers_html: { type: String, required: false },
    coverscreen_img: { type: String, required: false },
    logo_img: { type: String, required: false },
    background_img: { type: String, required: false },
    background_color: { type: String, required: false },
    event_fromdate: {type: Date, default: Date.now},
    event_todate: {type: Date, default: Date.now},
    attendees_feedback: { type: Boolean, required: false },
    social_network: { type: Boolean, required: false },
    feature_icon_color: { type: String, required: false }
    });
exports.EacEvent = mongoose.model("EacEvent", scheme);

我需要找到所有EacEvents,其中user _id等于这样的东西(56a8a1eaf7a3289c10c9ed30)我尝试了很多东西,但要么我得到了所有的EacEvent,要么没有EacEvent。感谢

路线档案

这是我用来获取所需结果的路线文件代码..

var models = require('../models')
    ,mongoose = require('mongoose')
    var schema = mongoose.Schema;
    var ObjectId = schema.ObjectId;
// var ObjectID = schema.ObjectId;
exports.myeventapps = function (req, res) {
    var eac_userid;
    if (req.user){
        eac_userid =  JSON.stringify(req.user._id);
        console.log('================================' + eac_userid);
    }
    //models.EacEvent.find().exec(function(err, myevents) {
    models.EacEvent.find({ deleted: false,'user._id':ObjectId(eac_userid)}).sort({ modified: -1 }).exec(function(err, myevents) {
        res.locals.myevents = myevents;     
        console.log('================================' + myevents);
        res.render('eac_myevent_apps', { title: "My Event Apps", myeventapps: myevents });
    });
}

我也试过在.populate()函数中比较user._id但是没有得到所需的结果

1 个答案:

答案 0 :(得分:0)

请尝试一下,直接与user字段匹配,而不是user._id。  请参阅Mongoose Populate

 models.EacEvent.find({ deleted: false, 'user': ObjectId(eac_userid)}).sort(...

也许我们可以直接使用req.user._id

 models.EacEvent.find({ deleted: false, 'user': req.user._id}).sort(...