简体   繁体   中英

Mongoose Populate returning ObjectID instead of content

I'm attempting to create a project scheduler application and I have 2 models so far, ProjectModel and ProjectTaskModel. However, when tryinng to populate, I only seem to get the objectID's of the tasks.

ProjectModel.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const projectModel = new Schema({
    title:{type:String,required:[true,"Project Title is required"]},
    desc:{type:String,required:true},
    status:{type:String,required:true},
    tasks:[{type:Schema.Types.ObjectId,ref:'Task'}]
})

module.exports = mongoose.model('Project',projectModel);

ProjectTask.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const projectTaskModel = new Schema({
    title:{type:String,required:[true,"Project Title is required"]},
    desc:{type:String,required:true},
    status:{type:String,required:true}
})

module.exports = mongoose.model('Task',projectTaskModel);

index.js

app.get('/project/:id',async(req,res) => {

    const project = await projectModel.findOne({_id:req.params.id});
    const test = project.populate('tasks');
    console.log(test);
    res.send(test);
})

Postman

{
    "tasks": [
        "6086ba5837f40a20cc5be2b2",
        "6086bd16c0f35353b848e6cc"
    ],
    "_id": "6086b85b26bc1e79ac34b135",
    "title": "Second project",
    "desc": "This is a projcet I did TO DO for myself",
    "status": "completed",
    "__v": 2
}

On Your ProjectModel.js you have initialized tasks as a type of Schema.Types.ObjectId and reference of 'Task' that's why when you tried this > project.populate('tasks') it's only sent back you the ids. If you want the full Task object, then do something like this, when you got the IDs of the task you make another request to your ' Task ' model with those ids and this time you will get your full object. Hope this will help you understand things.

I'm not sure if you have solved this yet or not, but here are two things I would try.

  1. Make your query call in one line instead of two.
  2. Use.exec() after populate.

In the end, it would look like this:

const project = await projectModel.findOne({_id:req.params.id}).populate('tasks').exec();

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