简体   繁体   English

数据库中的多层数组,无法将数组推入第二层

[英]Multilayered array in database, can't push array into second layer

In my database i have the following setup for testdata: 在我的数据库中,我对testdata进行了以下设置:

test1  [

   [0] { test: Array, comments: Array },
   [1] { test: Array, comments: Array }

]

Below is how i define the userSchema, it contains more but i think they are irrelevant in this scenario. 以下是我定义userSchema的方式,它包含更多内容,但我认为在这种情况下它们是不相关的。

var UserSchema = new Schema({

    test1: { type: Array, required: false },
    test2: { type: Array, required: false },
    test3: { type: Array, required: false }

});

Below is a part of the code that saves the data to the database. 以下是将数据保存到数据库的代码的一部分。 The "newTest1" is an array of comments. “ newTest1”是一个注释数组。 I've been trying to add a comment to the object but have been unable to. 我一直在尝试向对象添加评论,但一直无法这样做。 The idea is that i first add the data which creates the object (see api.js below) and then add the comments. 我的想法是,我首先添加创建对象的数据(请参见下面的api.js),然后添加注释。

No error is displayed, the array I'm trying to get into the object is just not added. 没有错误显示,我没有尝试添加到对象中的数组。 In the api.js (code snippet further down) I'm able to push into the first layer of the array but not the object within. 在api.js中(向下的代码段),我可以推入数组的第一层,但不能推入其中的对象。 This must mean that i can't see into the array from the database but i don't know why this is. 这必须意味着我无法从数据库中查看数组,但是我不知道为什么会这样。 I think if i somehow could get the array from the database, add the comments then user.save it would work but i don't know how to do that or if that is the best solution. 我想如果我能以某种方式从数据库中获取数组,则添加注释,然后user.save可以正常工作,但我不知道该怎么办,或者这是否是最佳解决方案。 Could someone help me out? 有人可以帮我吗?

html: HTML:

  <form name="edit.test1" ng-submit="ctrl.updateTest1(newComment1, newComment2, ctrl.artikel)">

    <div class="form-group">
        <label>Kommentarer:</label>
        <input class="form-control" type="text" name="test1" placeholder="Comment on first value" ng-model="newComment1" autocomplete="off">
        <br>
        <input class="form-control" type="text" name="test1" placeholder="Comment on second value" ng-model="newComment2" autocomplete="off">
    </div>

        <button type="submit" class="btn btn-primary">Submit</button>

  </form>

Controller: 控制器:

app.updateTest1 = function(newComment1, newComment2, index) {
          app.errorMsg = false; // Clear any error message
          app.disabled = true; // Lock form while processing
          // Check if username submitted is valid

              var userObject = {}; // Create the user object to pass to function
              userObject._id = app.currentUser; // Pass current user _id in order to edit

              userObject.test1 = [$scope.newComment1, $scope.newComment2, index]; // Set the new username provided

              // Runs function to update the user's username
              User.editUser(userObject).then(function(data) {

                // Behöver jag lägga till något här??

              });
            };

Userfactory: Userfactory:

  userFactory.editUser = function(id) {
        return $http.put('/api/edit', id);
    };

Creating a new user when a user registers: 用户注册时创建新用户:

router.post('/users', function(req, res) {
        var user = new User(); // Create new User object
        user.username = req.body.username; // Save username from request to User object
        user.password = req.body.password; // Save password from request to User object
        user.email = req.body.email; // Save email from request to User object
        user.name = req.body.name; // Save name from request to User object
        user.temporarytoken = jwt.sign({ username: user.username, email: user.email }, secret, { expiresIn: '24h' }); // Create a token for activating account through e-mail

        // Check if request is valid and not empty or null
        if (req.body.username === null || req.body.username === '' || req.body.password === null || req.body.password === '' || req.body.email === null || req.body.email === '' || req.body.name === null || req.body.name === '') {
            res.json({ success: false, message: 'Ensure username, email, and password were provided' });
        } else {
            // Save new user to database
            user.save(function(err) {
                if (err) {
                    // Check if any validation errors exists (from user model)
                    if (err.errors !== null) {
                        if (err.errors.name) {
                            res.json({ success: false, message: err.errors.name.message }); // Display error in validation (name)
                        } else if (err.errors.email) {
                            res.json({ success: false, message: err.errors.email.message }); // Display error in validation (email)
                        } else if (err.errors.username) {
                            res.json({ success: false, message: err.errors.username.message }); // Display error in validation (username)
                        } else if (err.errors.password) {
                            res.json({ success: false, message: err.errors.password.message }); // Display error in validation (password)
                        } else {
                            res.json({ success: false, message: err }); // Display any other errors with validation
                        }
                    } else if (err) {
                        // Check if duplication error exists
                        if (err.code == 11000) {
                            if (err.errmsg[61] == "u") {
                                res.json({ success: false, message: 'That username is already taken' }); // Display error if username already taken
                            } else if (err.errmsg[61] == "e") {
                                res.json({ success: false, message: 'That e-mail is already taken' }); // Display error if e-mail already taken
                            }
                        } else {
                            res.json({ success: false, message: err }); // Display any other error
                        }
                    }
                } else {
                    // Create e-mail object to send to user
                    var email = {
                        from: 'MEAN Stack Staff, cruiserweights@zoho.com',
                        to: [user.email, 'gugui3z24@gmail.com'],
                        subject: 'Your Activation Link',
                        text: 'Hello ' + user.name + ', thank you for registering at localhost.com. Please click on the following link to complete your activation: http://www.herokutestapp3z24.com/activate/' + user.temporarytoken,
                        html: 'Hello<strong> ' + user.name + '</strong>,<br><br>Thank you for registering at localhost.com. Please click on the link below to complete your activation:<br><br><a href="http://www.herokutestapp3z24.com/activate/' + user.temporarytoken + '">http://www.herokutestapp3z24.com/activate/</a>'
                    };
                    // Function to send e-mail to the user
                    client.sendMail(email, function(err, info) {
                        if (err) {
                            console.log(err); // If error with sending e-mail, log to console/terminal
                        } else {
                            console.log(info); // Log success message to console if sent
                            console.log(user.email); // Display e-mail that it was sent to
                        }
                    });
                    res.json({ success: true, message: 'Account registered! Please check your e-mail for activation link.' }); // Send success message back to controller/request
                }
            });
        }
    });

api.js: api.js:

    router.put('/edit', function(req, res) {
            var editUser = req.body._id; // Assign _id from user to be editted to a variable
            if (req.body.name) var newName = req.body.name; // Check if a change to name was requested
            if (req.body.username) var newUsername = req.body.username; // Check if a change to username was requested
            if (req.body.email) var newEmail = req.body.email; // Check if a change to e-mail was requested
            if (req.body.permission) var newPermission = req.body.permission; // Check if a change to permission was requested

            if (req.body.test1) {
              var newTest1 = req.body.test1;
            }
            if (req.body.test2) {
              var newTest2 = req.body.test2;
            }
            if (req.body.test3) {
              var newTest3 = req.body.test3;
            }
            if (req.body.test4) {
              var newTest4 = req.body.test4;
            }
            if (req.body.test5) {
              var newTest5 = req.body.test5;
            }


            // Look for logged in user in database to check if have appropriate access
            User.findOne({ username: req.decoded.username }, function(err, mainUser) {
                if (err) {
                    // Create an e-mail object that contains the error. Set to automatically send it to myself for troubleshooting.
                    var email = {
                        from: 'MEAN Stack Staff, cruiserweights@zoho.com',
                        to: 'gugui3z24@gmail.com',
                        subject: 'Error Logged',
                        text: 'The following error has been reported in the MEAN Stack Application: ' + err,
                        html: 'The following error has been reported in the MEAN Stack Application:<br><br>' + err
                    };
                    // Function to send e-mail to myself
                    client.sendMail(email, function(err, info) {
                        if (err) {
                            console.log(err); // If error with sending e-mail, log to console/terminal
                        } else {
                            console.log(info); // Log success message to console if sent
                            console.log(user.email); // Display e-mail that it was sent to
                        }
                    });
                    res.json({ success: false, message: 'Something went wrong. This error has been logged and will be addressed by our staff. We apologize for this inconvenience!' });
                } else {
                    // Check if logged in user is found in database
                    if (!mainUser) {
                        res.json({ success: false, message: "no user found" }); // Return error
                    } else {
                        // Check if a change to name was requested

-----> HERE               if (newTest1) {
                          // Check if person making changes has appropriate access
                          if (mainUser.permission === 'admin') {
                              // Look for user in database
                              User.findOne({ _id: editUser }, function(err, user) {
                                  if (err) {
                                      res.json({ success: false, message: 'Something went wrong. This error has been logged and will be addressed by our staff. We apologize for this inconvenience!' });
                                  } else {
                                      // Check if user is in database
                                      if (!user) {
                                          res.json({ success: false, message: 'No user found' }); // Return error
                                      } else {

                                            if (Array.isArray(newTest1)) {
                ------> this does not work   user.test1[0].comments.push(newTest1);
                                            //user.test1.splice(index, 0, newTest1)
                                          } else {
               ---> this works              var testet1 = { test: newTest1.split(" "), comments: Array };
                                            user.test1.push(testet1); // Assign new name to user in database
                                          }
                                          // Save changes
                                              user.save(function(err) {
                                                  if (err) {
                                                      console.log(err); // Log any errors to the console
                                                  } else {
                                                      res.json({ success: true, message: 'Name has been updated!' }); // Return success message
                                                  }
                                              });
                                      }
                                  }
                              });

Javascript arrays are always numbered indexes, and does not support named indexes. Javascript数组始终是带编号的索引,并且不支持命名索引。 Unless I missed something it looks like you are trying to create an associative array by giving it a named index which will not work. 除非我错过了一些事情,否则看起来您正在尝试通过给它命名的索引创建一个不起作用的关联数组。

First you need to make some tweaks at your Schema to make test1 array include objects with properties answers and comments and make them array too. 首先,您需要对Schema进行一些调整,以使test1数组包含具有属性answerscomments对象,并使它们也成为数组。 And then insert it to your main Schema like this: 然后将其插入到您的主模式中,如下所示:

var nestedSchema = new Schema ({
  answers: {type: Array, required: false},
  comments: {type: Array, required: false}
})

var UserSchema = new Schema({
    test1: { type: [nestedSchema], required: false },
    test2: { type: Array, required: false },
    test3: { type: Array, required: false }
});

Then user.test1[0].comments.push(newTest1) should work correctly. 然后, user.test1[0].comments.push(newTest1)应该可以正常工作。 Don't forget to pass the index of the needed answer when pushing new comment. 推送新评论时,请不要忘记传递所需答案的索引。 Like this user.test1[index].comments.push(newTest1) 像这样的user.test1[index].comments.push(newTest1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM