如何通过节点js和angularjs将数组添加到mongodb中?

时间:2017-06-06 05:53:43

标签: angularjs node.js mongodb

我的代码:

var user = new User({
    fullname: req.body.fullname,
    mobile:req.body.mobile,
    email: req.body.email,
    gender: req.body.gender,
    state: req.body.state,
    city: req.body.city,
    pincode:req.body.pincode,
    college: req.body.college,
    course: req.body.course,
    descipline: req.body.descipline,
    semester: req.body.semester,
    university: req.body.university,
    month:req.body.month,
    worklocation:req.body.worklocation,
    members:members
});

user.save(function(err, data) {
    if(err) {
        return next(err);
    }
    res.status(201).json(data);
});

1 个答案:

答案 0 :(得分:0)

您可以直接在架构中分配对象的成员数组

var members = [{degree_name:'xxx', degree_subject: 'yyy'},
              {degree_name:'xxx1', degree_subject: 'yyy1'}];

var user = new User({
            fullname: req.body.fullname,
            .....
            members:members
        });

如果您从angular发送相同的属性名称,则可以使用req.body之类的new User(req.body)

所以你可以从UI发送asq body,如

$scope.user = {
            fullname: 'xx',
            mobile: 'yy',
            members: [{degree_name:'xxx', degree_subject: 'yyy'},
                  {degree_name:'xxx1', degree_subject: 'yyy1'}]
};

然后在mongoose可以使用像

var user = new User(req.body); 

然后根据您的属性名称自动映射。

如果req.body属性名称与架构有任何不同,则重新分配该属性。

var user = new User(req.body); 
user.course = req.body.courseName

角度代码:

$scope.members = [{degree_name:'xxx', degree_subject: 'yyy'},
              {degree_name:'xxx1', degree_subject: 'yyy1'}];
  $scope.registerDetails = function() {
    $scope.user.members = $scope.members;
    $http.post('/api', $scope.user).success(function(data) {
      // your code
    }).error(function(status) {
      // your code
    });
  };