Mongoose:将另一个文档的 ref 保存到对象数组文档 returns 空数组中

Mongoose: Saving ref of another document into an array of objects document returns empty array

我正在尝试将特定文档的引用 ID 添加到另一个文档的对象数组中。这样我就可以使用填充方法。但不知何故,即使在按下 ref 之后,数组仍然是空的。 请帮我。提前谢谢你。

这里是list.js:

  const mongoose = require('mongoose');

  const User = require('./user');
  const Task = require('./task');
  const Schema = mongoose.Schema;
  // User Schema
  const ListSchema = mongoose.Schema({
    item:{
      type: String,
      required: true
    },
    purpose:{
      type: String,
      required: true
    },
    user: {
      type: Schema.ObjectId,
      ref:"User"
    },
    deadline:{
      type: Date,
      default: null
    }
  });

  const List = module.exports = mongoose.model('List', ListSchema);

task.js:

  const mongoose = require('mongoose');
  const Schema = mongoose.Schema;
  const List = require('./list');
  // User Schema
  const TaskSchema = mongoose.Schema({
    task:{
      type: String,
      required: true
    },
    list: [{
      type: Schema.Types.ObjectId,
      ref:'List'
    }]

  });

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

以下是我创建和保存新任务实例的方法:

  const express = require('express');
  const mongoose = require('mongoose');
  const router = express.Router();

  let List = require('../models/list');
  let User = require('../models/user');
  let Task = require('../models/task');

  router.post('/add', isAuthenticated, function(req,res){
    var tasker = req.body.task, listshash= [];
    var startIndex = 0, index;
      var x,y,listid= [];
      while ((index = tasker.indexOf("#", startIndex)) > -1) {
        var ind = tasker.indexOf(" ", index);
        if(ind == -1)
            listshash.push(tasker.substring(index+1));
      else  
          listshash.push(tasker.substring(index+1,ind));
          startIndex = index + 1;
      }

      //Instance of task
      var taskIns = new Task({task: req.body.task});

      List.find({user: req.session.passport.user}, function(err, lists){
      for(x in lists){
        for(y in listshash){
          if(lists[x].item.toLowerCase().replace(/\s/g,'') == listshash[y]){
            //lists[x] contains the document "list" that I want to store as 
            //ref in list property array of task
            taskIns.list.push(lists[x]);
            //console.log(taskIns.list.push(lists[x]));

          }
        }
      }
    });
    taskIns.save(function(err, doc){
        if(err) res.json(err);
        else    {
          console.log("Saved");
          res.redirect('/lists');
      }
    });
  });
  module.exports = router;

这是插入数据后数据库任务集合的样子: See the data

它没有保存引用,因为你正在处理异步函数;您正在 find() 回调中推送列表,并且 taskIns 模型保存事件发生在推送之前。

您可以在 find() 回调中移动 taskIns 保存操作或使用 promises 来解决问题。

例如,使用回调:

List.find({ user: req.session.passport.user}, (err, lists) => {

    const taskIns = new Task({task: req.body.task});

    for(x in lists) {
        for(y in listshash) {
            if(lists[x].item.toLowerCase().replace(/\s/g,'') == listshash[y]) {
                taskIns.list.push(lists[x]);
            }
        }
    }

    taskIns.save((err, doc) => {
        if(err) res.json(err);
        else {
          console.log("Saved");
          res.redirect('/lists');
        }
    });
});

你应该使用 async npm

List.find({user: req.session.passport.user}, function(err, lists){
     async.each(lists ,function(x,callback){
          async.each(listhash, function(y,callback){
               if(x.item.toLowerCase().replace(/\s/g,'') == y){
                   taskIns.list.push(x);
               }
          });
     });


//After that you can do save the data
  taskIns.save(function(err, doc){
        if(err) res.json(err);
        else    {
          console.log("Saved");
          res.redirect('/lists');
      }
    });
  });