使用NodeJS和Mongoose将数据插入架构数组

时间:2018-08-01 16:48:09

标签: javascript node.js mongoose

我有下一个模式:

'use strict';

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

const userSchema = Schema({
  id: String,
  name: [{
    name: String,
    surname1: String,
    surname2: String,
  }]
});

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

然后我创建了下一个函数:

module.exports.signUp = function(req,res){
  console.log('POST signUp');
  let user = new User();

  for(var key in req.body) {
    console.log(key);
    switch (key) {
      case 'name[name]':
        user.name.push({name:"name"});
      break;
      case 'name[surname1]':
        user.name.push({surname1:"surname1"});
      break;
      case 'name[surname2]':
        user.name.push({surname2:"surname2"});
      break;
    }
  }         
  res.status(202).send({message: user});
}

我需要下一个结果:

{
    "message": {
        "_id": "5b61e242c4874a045dd4185a",
        "name": [
            {
                "name": "name",
                "surname1": "surname1",
                "surname2": "surname2"
            }
        ]
    }
}

我得到:

{
    "message": {
        "_id": "5b61e242c4874a045dd4185a",
        "name": [
            {
                "_id": "5b61e242c4874a045dd4185b",
                "name": "name"
            },
            {
                "_id": "5b61e242c4874a045dd4185c",
                "surname1": "surname1"
            },
            {
                "_id": "5b61e242c4874a045dd4185d",
                "surname2": "surname2"
            }
        ]
    }
}

它生成_id的倍数和不同的JSON格式。

我尝试了user.name[0]="name", user.name.name="name",但不起作用... 当我尝试user.name = {"name":"name"}有效时,但之后 user.name = {"surname1":"surname1"}并且名称不存在。

能帮我吗? 谢谢!

1 个答案:

答案 0 :(得分:0)

您正在遍历req.body并每次按一个键。您需要一次完成所有操作。像

const name={};
if ('name[name]' in req.body){name.name=req.body['name[name]'];}
if ('name[surname1]' in req.body){name.surname1=req.body['name[surname1]'];}
if ('name[surname2]' in req.body){name.surname2=req.body['name[surname2]'];}
user.name.push(name);

尽管名称数组中的每个条目都在Mongo中被声明为子文档,但它们将具有单独的ID。您仍然可以通过其ID访问该用户,但是您还可以分别访问每个名称对象。

如果每个用户只需要一个名称,则可以将架构简化为

const userSchema = Schema({
  id: String,
  name: {
    name: String,
    surname1: String,
    surname2: String,
  }
});

然后将名称对象设置为

user.name=name;