홈>
내 로컬 DB의 데이터 배열에 주석을 추가하는 방법을 알아 내려고 노력했습니다. 내가 지금하고있는 아이디어는 데이터 배열에 주석 배열을 추가하여 어떤 주석이 어떤 데이터 세트에 있는지 쉽게 알 수 있도록하는 것입니다. 다음 코드를 사용하여 시도하면 작동하지 않습니다.
(이것은 데이터를 보유 할 배열을 정의하는 userchema에 있습니다)
test1: { type: array, required: false }
(다음으로 푸시로 주석 배열을 추가하려고하지만 작동하지 않습니다. 테스트 0을 예제로 사용하고 있습니다. 일반적으로 주석을 추가하려는 테스트에 따라 다릅니다. 주석을 추가하려는 해당 데이터로 더 많은 배열을 바꿉니다. 그래서 user.test1 [0])
user.test1[0].push(newComment);
(다음은 스플 라이스를 사용하는 동안에는 작동하지 않습니다)
user.test1.splice(1, 0, newComment)
어떤 이유로 인해 user.test1 [0]에 액세스 할 수없는 것처럼 보이지만 왜 그런지 모르겠습니다. 아니면 테스트에 주석을 추가 할 때 다른 기술을 사용해야합니까?
<시간>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];
User.editUser(userObject).then(function(data) {
});
};
userFactory.editUser = function(id) {
return $http.put('/api/edit', id);
};
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 firstTest2 = req.body.test2;
var newTest2 = firstTest2.split(" ");
}
if (req.body.test3) {
var firstTest3 = req.body.test3;
var newTest3 = firstTest3.split(" ");
}
if (req.body.test4) {
var firstTest4 = req.body.test4;
var newTest4 = firstTest4.split(" ");
}
if (req.body.test5) {
var firstTest5 = req.body.test5;
var newTest5 = firstTest5.split(" ");
}
// 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
if (newName) {
// Check if person making changes has appropriate access
if (mainUser.permission === 'admin' || mainUser.permission === 'moderator') {
// Look for user in database
User.findOne({ _id: editUser }, function(err, user) {
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 user is in database
if (!user) {
res.json({ success: false, message: 'No user found' }); // Return error
} else {
user.name = newName; // 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
}
});
}
}
});
} else {
res.json({ success: false, message: 'Insufficient Permissions' }); // Return error
}
}
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 {
-> (this is where i think the problem is) if (Array.isArray(newTest1)) {
var index = newTest1[2];
-> this doesn't work user.test1[0].push(newTest1);
//user.test1.splice(index, 0, newTest1)
} else {
var testet1 = newTest1.split(" ");
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
}
});
}
}
});
} else {
res.json({ success: false, message: 'Insufficient Permissions' }); // Return error
}
}
- 답변 # 1
관련 질문
- javascript : 배열에서 다중 값 객체 배열을 만드는 JS
- javascript : 데이터가 정의되지 않은 경우 하나 이상의 속성이 있어야 합니다.
- javascript : 문자열 기반 빈 줄 분할 및 구분 기호 기반 개체 생성
- javascript : 사전 정의된 JS의 숫자, 문자열, 부울, 배열의 프로토타입 체인을 수동으로 끊거나 값을 재할당할 수 있습니까?
- javascript : Node.js: 콜백이 오류를 반환합니다.
- javascript : 서버에 업로드할 때 typescript를 js로 빌드해야 하나요?
- javascript : Telegram 봇에서 PostgreSQL에 데이터를 삽입할 수 없습니다.
- javascript : nodejs에서 redis에 연결할 수 없습니다
- javascript : 잡히지 않은 오류: 모듈 빌드 실패(./node_modules/babel-loader/lib/index.js에서)
- javascript : Node JS의 API 응답에서 속성을 얻는 방법은 무엇입니까?
user.test1[0]
를 확인해야합니다 값은 조작하기 전에 존재합니다. 당신의user.test1
경우배열에는 값이 전혀 없으며 아무 것도 넣을 수 없습니다.