Mongoose가 배열 내에서 문서를 삭제(풀)하고 개체와 함께 작동하지 않습니다.아이디
다음과 같은 몽구스 스키마가 있습니다.
user = {
"userId" : "myId",
"connections":
[{
"dateConnectedUnix": 1334567891,
"isActive": true
}, {
"dateConnectedUnix": 1334567893,
"isActive": false
}]
}
다음의 두 번째 항목을 삭제하고 싶습니다.connections
배열, 다음을 가져옵니다.
user = {
"userId" : "myId",
"connections":
[{
"dateConnectedUnix": 1334567893,
"isActive": false
}]
}
다음 코드는 예상대로 작동합니다.
userAccounts.update(
{ 'connections.isActive': false },
{ $pull: { 'connections.isActive':false }},
function (err, val) {
console.log(val)
}
);
하지만 ObjectId를 기준으로 삭제해야 합니다.그리고 다음은 작동하지 않습니다.
userAccounts.update(
{ 'connections._id': '1234-someId-6789' },
{ $pull: { 'connections._id': '1234-someId-6789' } },
function (err, val) {
console.log(val)
}
);
좋은 의견이라도 있나?저는 몇 시간 동안 화면(일명 Google, Stackoverflow 등)에 머리를 부딪혔지만 운이 없었습니다.
위의 코드가 작동하지 않는 것 같습니다.제가 제시한 첫 번째 예에서는 작동하지 말았어야 했습니다.
결국 저는 여기서 이 대답을 지지했습니다: MongoDB, 배열에서 객체 제거
다음은 내 작업 코드입니다.
userAccounts.update(
{ userId: usr.userId },
{
$pull: {
connections: { _id : connId }
}
},
{ safe: true },
function removeConnectionsCB(err, obj) {
// ...
}
);
다음과 같은 문서가 있습니다.
주소 배열에서 주소를 삭제해야 합니다.
인터넷에서 많은 것을 검색한 후에 해결책을 찾았습니다.
Customer.findOneAndUpdate(query, {$pull: {address: addressId}}, (err, data) => {
if (err) {
return res.status(500).json({ error: 'error in deleting address' });
}
res.json(data);
});
user: {
_id: ObjectId('5ccf3fa47a8f8b12b0dce204'),
name: 'Test',
posts: [
ObjectId("5cd07ee05c08f51af8d23b64"),
ObjectId("5cd07ee05c08f51af8d23c52")
]
}
게시물 배열에서 단일 게시물 제거
user.posts.pull("5cd07ee05c08f51af8d23b64"); user.save();
ObjectId로 업데이트를 사용하려면 문자열 표현 대신 ObjectId 개체를 사용해야 합니다.
var ObjectId = require('mongoose').Types.ObjectId;
userAccounts.update(
{ 'connections._id': new ObjectId('1234-someId-6789') },
{ $pull: { 'connections._id': new ObjectId('1234-someId-6789') } },
function (err,val) {
console.log(val)
}
);
사용하다findByIdAndUpdate
배열에서 항목을 제거하다
에서 할 수 있습니다.
const result = await User.findByIdAndUpdate(user_id, {
$pull: {
someArrayName: { _id: array_item_id }
}
}, { new: true });
제공된 속성을 기준으로 어레이의 항목이 제거됩니다._id
가치
사용 중인 경우mongoose
를 사용할 필요가 없습니다.MongoDB
내 말은, 그게 우리가 사용하는 이유야.mongoose
애당초에, 그렇죠?
userAccounts.connections.pull({ _id: '1234-someId-6789'});
await userAccounts.save();
몽구스: 4.11.11
저에게 효과가 있었던 것은 다음과 같은 구문입니다.
const removeTansactionFromUser = (userId, connectionId) => {
return User.findByIdAndUpdate(userId, { $pull: { "connections": connectionId} }, {'new': true} );
};
문자열 형식 또는 ObjectId 형식의 Mongoose 지원 ID입니다.
팁:new ObjectId(stringId)
문자열에서 ObjectId로 전환
mongoose 5.8.11에서, 이것은$pull: { ... }
왜 그런지 아직까지는 잘 모르겠어요그래서 저는 컨트롤러에서 다음과 같은 방식으로 극복했습니다.
exports.removePost = async (req, res, next) => {
const postId = req.params.postId;
try {
const foundPost = await Post.findById(postId);
const foundUser = await User.findById(req.userId);
if (!foundPost || !foundUser) {
const err = new Error(
'Could not find post / user.',
);
err.statusCode = 404;
throw err;
}
// delete post from posts collection:
await Post.findByIdAndRemove(postId);
// also delete that post from posts array of id's in user's collection:
foundUser.posts.pull({ _id: postId });
await foundUser.save();
res.status(200).json({ message: 'Deleted post.' });
} catch (err) {
// ...
}
};
언급URL : https://stackoverflow.com/questions/19786075/mongoose-deleting-pull-a-document-within-an-array-does-not-work-with-objectid
'programing' 카테고리의 다른 글
git log에서 지점 이름을 표시하려면 어떻게 해야 합니까? (0) | 2023.07.18 |
---|---|
판다 데이터 프레임 내의 열을 int에서 string으로 변환 (0) | 2023.07.18 |
PL/SQL의 숨겨진 기능 (0) | 2023.07.18 |
SQL*Plus에서 잘못된 형식 지정 (0) | 2023.07.18 |
동적 SQL 결과를 변수에 할당 (0) | 2023.07.18 |