Express: POST 数据到数组 mongoose 和节点

Posted

技术标签:

【中文标题】Express: POST 数据到数组 mongoose 和节点【英文标题】:Express: POST data to an array mongoose & node 【发布时间】:2017-11-17 15:10:19 【问题描述】:

我正在构建一个简单的应用程序,一家公司在其中向员工发送问题以征求反馈意见。我正在努力将更多员工(用户)作为数组放入问题文档中。现在它只插入一名员工。基本上我需要的是让员工对每个问题做出回应,并且能够(将来)查询数据库以获取员工回答的所有问题。这是我的架构。

这里是previous issue that was solved - 任何感兴趣的人。

模型

var QuestionSchema = Schema(
    id          : ObjectId,
    title       : String,
    employees   : [ type: ObjectId, ref: 'User']
);

module.exports = mongoose.model('Question', QuestionSchema);  

var UserSchema = Schema(
    username    : String,
    response    : String,
    questions   : [ type: ObjectId, ref: 'Question']
);

module.exports = mongoose.model('User', UserSchema);

api.js

         Question.findOne( title: 'Should we buy a coffee machine?').exec(function(err, question) 
              //example: is this the right way of creating the array
              var user = new User([
                "username": "lindelof",
                "response": "yes",
              ,
                "username": "bailly",
                "response": "no",
              ,
                "username": "suzan",
                "response": "yes",
              ]);

              question.employees = [user1._id];
              user.questions = [question._id];

              question.save(function(err) 
                  if (err) throw err;
                  console.log(question);
                  user1.save(function(err) 
                      if (err) throw err;
                  );
              );

            );
            console.log('entry saved to answer >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
        

【问题讨论】:

【参考方案1】:

我会这样修改你的 api.js:

Question.findOne( title: 'Should we buy a coffee machine?').exec(function(err, question) 
  const userData = [
    "username": "lindelof",
    "response": "yes",
  ,
    "username": "bailly",
    "response": "no",
  ,
    "username": "suzan",
    "response": "yes",
  ];

  for (const user of userData) 
    const userModel = new User(user);
    userModel.questions = [question._id];
    // Its async, but in this example - no need to wait untill it is executed
    userModel.save();
    question.employees.push(userModel._id);
  

  question.save(function(err) 
    if (err) throw err;
    console.log(question);
  
);

另外,我可以建议你看看 promises/generators 或 async/await 方法。这样阅读起来就容易多了。

使用 async/await 格式化的相同代码:

async function doJob() 
  const question = await Question.findOne( title: 'Should we buy a coffee machine?');

  const userData = [
    "username": "lindelof",
    "response": "yes",
  ,
    "username": "bailly",
    "response": "no",
  ,
    "username": "suzan",
    "response": "yes",
  ];

  for (const user of userData) 
    const userModel = new User(user);
    userModel.questions = [question._id];
    await userModel.save();
    question.employees.push(userModel._id);
  

  await question.save();
  console.log(question);

;

// And sure we have to call this function somewhere...
doJob();

【讨论】:

工作感谢! async 方法虽然指向 async function doJob(),但会引发“SyntaxError: Unexpected token function”错误 很可能你有旧的nodejs版本,更新它。

以上是关于Express: POST 数据到数组 mongoose 和节点的主要内容,如果未能解决你的问题,请参考以下文章

使用节点将对象数组保存到 mongo 数据库,表达

POST http://localhost:3001/createPost 404 (Not Found) EXPRESS & REACT

夺命雷公狗---node.js---22之项目的构建在node+express+mongo的博客项目7之数据的修改

检查 Express 请求数据是不是为数组

使用mongo-express管理mongodb数据库

无法使用 Express.js 从请求中获取 POST 正文