findOneAndUpdate 메서드에서 업데이트된 문서를 다시 가져오는 방법은 무엇입니까?
는 노드를 사용하고 , 는 mongoDB를 사용했습니다.npm install mongodb
기존 문서를 업데이트하고 업데이트된 문서를 반환하고 싶습니다. 문서가 올바르게 업데이트되었습니다. 그러나 이전 문서는 업데이트 전의 원본 문서를 반환합니다. 저는 사용했습니다.returnNewDocument:true
매개 변수이지만 사용되지 않습니다.
var filter = {
'_id': object_id
},
update = {
$set: { "status" : data["status"] },
$push: {
"statusHistory": {
$each: [{ status:data["status"],statusChangedTime:data["statusChangedTime"],comment:data["comment"]}],
$position:0,
}
},
}
,options = {
//upsert: false,
//multi: false,
returnNewDocument: true
};
col.findOneAndUpdate(filter, update, options,function(err, res) {
if (err) {
console.log(err);
}else {
console.log(res);
}
});
반응은
{ lastErrorObject: { updatedExisting: true, n: 1 },
value:
{
//original document
},
ok: 1 }
터미널을 통해 mongoDB로 직접 가서 시도할 때
db.MyCollection.find().pretty();
문서가 올바르게 업데이트되었습니다. 업데이트된 문서가 아닌 원본만 반환됩니다.
2시간 동안 여기에 갇혀 있으면 어떤 도움이든 감사합니다.
꾸러미로제이손
"mongodb": "^2.1.4",
Node.js 드라이버 설명서에는 다음과 같은 내용이 나와 있지 않습니다.returnNewDocument
을 선택할 수 .findOneAndUpdate()
(동일한 이름의 MongoDB shell 명령에 대한 옵션).
대신, 다음과 같은 옵션을 언급합니다.returnOriginal
기본값은 다음과 같습니다.true
해서 이옵을사용다설음정합다니로으여로 설정해 보세요.false
원본 대신 업데이트된 문서를 반환합니다.
업데이트 작업을 수행한 후 업데이트된 문서를 가져오려면 옵션을 사용해야 합니다."returnDocument" : "after"
"returnOriginal" : false
.
최신 mongodb 노드 드라이버 v3.6 설명서에 따르면 returnOriginal은 더 이상 사용되지 않습니다.하지만 내가 오직 포함하려고 할 때."returnDocument" : 'after'
없이"returnOriginal":false
업데이트된 레코드 대신 원래 레코드를 반환합니다.둘 다 사용하면 원래 레코드 대신 업데이트된 레코드의 원하는 출력이 제공됩니다.(출처 : http://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#findOneAndUpdate)
»"returnNewDocument" : true
mongo 셸 옵션이며 공식 mongodb 설명서에 따라 노드 드라이버에서 작동하지 않을 수 있습니다(여기서 언급됨 https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/) ).
이 최신 2018년을 보고 있는 경우 새 문서:true를 반환하거나 원본:false를 반환하지 마십시오.대신 쿼리에 대한 옵션 개체의 {..., new:true}에서처럼 new라는 속성을 true로 설정해야 합니다.
노드JS MongoDB 드라이버는 명령에 대한 네이티브 MongoDB 셸과 비교하여 다른 인수를 가집니다.findOneAndUpdate()
이 ""^한다면, "mongodb": "^2.1.4"를 사용하세요.
원본 반환: false
대신
새 문서 반환: true
.
다음 코드를 살펴보겠습니다.
db.collection('user_setting').findOneAndUpdate({user_id: data.user_id}, {$set: data}, {projection: dbConfig.userSetting, returnOriginal: false}, function (err, res) {
if (err) {
callback({'error': 1, 'message': 'Internal server error! ' + err, 'data': null, 'status': 500});
} else {
console.log(res);
/* { lastErrorObject: { updatedExisting: true, n: 1 },
value:
{ user_id: 1,
notification_alert: 1,
notification_sound: 1,
user_setting_id: 2
},
ok: 1
} */
}
});
2021년 8월
node.js 클라이언트의 v4가 출시되면서 이전 솔루션인 것으로 보입니다.returnOriginal: false
(어쨌든 끔찍했던 것은) 더 이상 정답이 아닙니다.
node.js findOneAndUpdate 메서드에 대해 사용 가능한 옵션 목록을 보려면 https://mongodb.github.io/node-mongodb-native/4.0/interfaces/findoneandupdateoptions.html
하지만 간단히 말해서, 이것은 효과가 있을 것입니다.
const doc = await <Collection>.findOneAndUpdate(
{ ... search },
{
$set: {
field1: 'value 1',
field2: ['value 2'],
etc.
},
},
{
upsert: true,
returnDocument: 'after', // this is new !
}
)
사용 중에 다른 사용자가 이 문제에 직면한 경우{ returnOriginal: false }
Mongoose 설정 내:
몽구스 사용법{ new: true }
대신에{ returnOriginal: false }
.
이 기능은 Mongoose: findOneAndUpdate가 업데이트된 문서와 Mongoose 문서 내에서 반환하지 않습니다.
옵션:
new: bool - true이면 원본이 아닌 수정된 문서를 반환합니다. 기본값은 false입니다(4.0 참조).
그래서 사용할 때findOneAndUpdate
더하다new: true
메서드 옵션:
...
const options = {
new: true
};
col.findOneAndUpdate(filter, update, options, function (err, res) {
if (err) {
console.log(err);
} else {
console.log(res);
}
});
4.0+에 대한 실제 소스 코드 및 유형 정의에 따르면 새 속성은 다음과 같습니다.new
설정true
수정된 결과를 반환합니다.
interface QueryFindOneAndUpdateOptions extends QueryFindOneAndRemoveOptions {
/** if true, return the modified document rather than the original. defaults to false (changed in 4.0) */
new?: boolean;
...
나는 몽구스를 사용하고 있습니다: 5.8.
이 행들을 아래에 두고.
const option = { new: true }
const account = await Account.findOneAndUpdate(filter, update, option)
그리고 이것은 효과가 있습니다.
이것은 저에게 효과가 있었습니다.
req.db.collection(collectionName).findOneAndUpdate(
{ _id : commentById._id }, // matching parameters
updateOpts, //updating parameters
{returnOriginal: false} //don't use **returnNewDocument**
);
언급URL : https://stackoverflow.com/questions/35626040/how-to-get-updated-document-back-from-the-findoneandupdate-method
'programing' 카테고리의 다른 글
활동 컨텍스트 외부에서 시작 활동() 호출 (0) | 2023.05.31 |
---|---|
강제 업데이트 후 Git Pull (0) | 2023.05.31 |
웹 뷰가 URL 로드를 마치기 위해 듣는 방법은 무엇입니까? (0) | 2023.05.31 |
제안된 내용 간격띄우기에 대한 대상 내용 간격띄우기:UICollectionViewFlowLayout을 하위 분류하지 않고 스크롤 속도 사용 (0) | 2023.05.31 |
UI Picker 보기 높이를 변경하는 방법 (0) | 2023.05.31 |