【问题标题】:Mongoose .Populate() returns empty arrayMongoose .Populate() 返回空数组
【发布时间】:2019-06-05 22:10:28
【问题描述】:

我不明白问题是什么。 以及为什么“任务”数组中的每个元素都是空的。

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

创建新用户时我添加默认任务

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

获取用户任务

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

});
});

.Populate() 之前的控制台.log {

{ 任务:[ 5cf78ac1d08ee617fc89f7ed, 5cf78ac1d08ee617fc89f7ee ]

在 { { 任务:[] 之后,

请帮忙!我发现的一切都没有解决我的问题。 defaultTasks 中可能有问题。但我没看到。

【问题讨论】:

  • 我的猜测是您没有将任务保存到数据库。您可以检查您的任务集合是否为空。
  • 感谢您的回复。在 DB 中,我有 Collection TaskManager.users.tasks 数组,有 2 个 id。我没有 TaskManager.tasks

标签: javascript node.js mongodb express mongoose


【解决方案1】:

您的代码不会将您的任务保存到数据库,它只是创建一个对象。因此,稍后当您填充用户时,在数据库中找不到任何任务。

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

// or

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

附:当然你可以按照你想要的方式处理异步调用。

【讨论】:

  • 我不保存到数据库所以这是我在注册部分的解决方案:code User.create(newUser) .then(user => { Task.insertMany(defaultTasks, function(error, task) { console.log('Add defaults');});
猜你喜欢
  • 2013-12-17
  • 2015-08-16
  • 2013-05-22
  • 2021-09-16
  • 2016-12-24
  • 2019-11-29
  • 1970-01-01
  • 2013-11-23
相关资源
最近更新 更多