2017-08-05 8 views
0

に配列をプッシュすることはできません私は、テストデータのための次の設定があります。多層配列は、私のデータベースでは、第二層

以下
test1 [ 

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

] 

iがuserSchemaをどう定義するか、それはより多く含まれているのが、私は彼らがいると思いますこのシナリオでは無関係です。

var UserSchema = new Schema({ 

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

}); 

以下は、データをデータベースに保存するコードの一部です。 "newTest1"はコメントの配列です。私はオブジェクトにコメントを追加しようとしていましたが、できなかったのです。アイデアは、まず、オブジェクトを作成するデータを追加し(以下のapi.jsを参照)、コメントを追加することです。

エラーは表示されません。オブジェクトに到達しようとしている配列は追加されません。 api.js(さらにコードスニペット)では、配列の最初のレイヤーにプッシュすることはできますが、オブジェクトは入れません。これは、データベースから配列を見ることができないことを意味する必要がありますが、なぜこれがわからないのですか?私は何とかデータベースから配列を取得できたら、コメントを追加してからuser.saveを呼び出すことができますが、それを行う方法がわからない場合や、それが最適な解決策であるかどうかはわかりません。誰かが私を助けてくれますか?

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> 

コントローラー:

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.editUser = function(id) { 
     return $http.put('/api/edit', id); 
    }; 

たときに、ユーザー登録:

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, cruiserw[email protected]', 
         to: [user.email, '[email protected]'], 
         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:

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, [email protected]', 
         to: '[email protected]', 
         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 
                } 
               }); 
             } 
            } 
           }); 

答えて

0

まず、あなたのスキーマでいくつか微調整をして、プロパティanswerscommentsのtest1配列インクルードオブジェクトを作成して配列にする必要があります。そして、このようなあなたのメインのスキーマにそれを挿入します。

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 } 
}); 

その後user.test1[0].comments.push(newTest1)が正しく動作するはずです。新しいコメントを押すときに、必要な答えのインデックスを渡すことを忘れないでください。このようにuser.test1[index].comments.push(newTest1)

0

Javascriptの配列は常にインデックス番号が付けられている、と名前のインデックスをサポートしていません。私が何かを見逃していない限り、あなたは連想配列を作成しようとしているように見えます。

+0

まあ、大丈夫です。コメントを追加することで、どうやって行くのですか? – Oscar

関連する問題