简体   繁体   中英

node.js mongoose foreign key retrieval

I have a project entity and its tasks (one to many relation). the task has a foreign key reference to project.

This is my model for Task

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;


var TaskTemplateSchema = new Schema({

    title: {
        type: String
    },
    projectTemplate: {
        type: Schema.ObjectId,
        ref: 'ProjectTemplate'
    },

    index: {
        type: Number
    }

})

mongoose.model('TaskTemplate', TaskTemplateSchema)

my model for Project

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var ProjectTemplateSchema = new Schema({

    title: {
        type: String
    },

    taskTemplateInfo: {
        type:String
    },

    creator: {
        type: Schema.ObjectId,
        ref: 'User'
    }

})

mongoose.model('ProjectTemplate', ProjectTemplateSchema)

Now i want to retrieve a list of tasks which belong to a certain project.

exports.projectTemplateById = function(req, res, next, id) {

    ProjectTemplate.findById(id).populate('creator', 'firstName lastName fullName').exec(function(err, projectTemplate) {
        if (err) return next(err)
        if (!projectTemplate) return next(new Error('failed to load project template ' + id))
        req.projectTemplate = projectTemplate

        //TODO: NOT FINDING ANYTHING?
        TaskTemplate.find({'projectTemplate': projectTemplate}).exec(function(err, taskTemplates) {
            if (err) return next(err)
            req.projectTemplate.taskTemplates = taskTemplates
            next()
        })

    })

}

Note this section of the above code:

TaskTemplate.find({'projectTemplate': projectTemplate}). 

does not return any tasks. I have tried projectTemplate._id , as well as projectTemplate._id.id , projectTemplate._doc.id , but none of above works

[EDIT]

When i try today, i was able to retrieve the array. I think the problem may be here:

exports.read = function(req, res) {
    res.json(req.projectTemplate)
}

read function is called when user request the projectTemplate. The taskTemplates attribute is present, but it is not defined in the mongoose model. The taskTemplates does not exist in the returned json.

The following code is working:

var str = JSON.stringify(req.projectTemplate)
req.projectTemplate._doc.taskTemplates = req.projectTemplate.taskTemplates
str = JSON.stringify(req.projectTemplate)
res.send(JSON.stringify(req.projectTemplate))

I guess it's because only _doc attributes are converted to json.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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