简体   繁体   中英

Mongoose .Populate() returns empty array

I do not understand what the problem is. And why each element from the 'tasks' array is null.

Schema = mongoose.Schema;

const userSchema = new Schema({
    email: {
    type: String,
    required: true 
},  
password: {
    type: String,
    required: true 
},
tasks: [{type: Schema.Types.ObjectId, ref: 'Task'}]
}
);

const taskSchema = new Schema({
title: String
});

const User = mongoose.model('User', userSchema);
const Task = mongoose.model('Task', taskSchema);

// Add some default to DB
const task1 = new Task({
title: "Welcome! Here You Can:"
});

const task2 = new Task({
title: "ADD EDIT DELETE SHARE your TASKS "
});

const defaultTasks = [task1, task2];

When create new User I Add defaultTasks

const newUser = {
    email: req.body.email,
    password: req.body.password,
    tasks: defaultTasks
};

Get Users Tasks

app.get('/tasks/', function(req, res){
const email = req.query.user;  
User
    .findOne({email: email})
    .populate('tasks')
    .exec()
    .then(foundUser => {

        console.log(foundUser);
        const data = [];
        Object.keys(foundUser.tasks).forEach(function(key) {
        const val = foundUser.tasks[key];
        data.push([val.title, val._id]);
    });
    res.send(data);
    console.log('Data to send ' + data);        

});
});

Before .Populate() console.log {

{ tasks: [ 5cf78ac1d08ee617fc89f7ed, 5cf78ac1d08ee617fc89f7ee ]

After { { tasks: [],

Please Help! All that I found did not solve my problem. Maybe problem in defaultTasks. But i dont see it.

Your code doesn't save your task to DB, it just creates an object. So later when you populate User there are no tasks in DB to be found.

 const task1 = await new Task({ title: "Welcome! Here You Can:" }).save(); // or const task1 = await Task.create({ title: "Welcome! Here You Can:" }); 

Ps of course you can deal with asynchronous calls the way you want.

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