반응형
Mongoose에서 _id to db 문서를 설정하는 방법?
나는 db에 있는 문서를 세고 그 숫자를 사용하여 _id를 생성함으로써 내 Mongoose 모델을 위한 _id를 동적으로 생성하려고 합니다(첫 번째 _id는 0이라고 가정합니다).하지만 제 값에서 _id를 설정할 수 없습니다.내 코드는 다음과 같습니다.
//Schemas
var Post = new mongoose.Schema({
//_id: Number,
title: String,
content: String,
tags: [ String ]
});
var count = 16;
//Models
var PostModel = mongoose.model( 'Post', Post );
app.post( '/', function( request, response ) {
var post = new PostModel({
_id: count,
title: request.body.title,
content: request.body.content,
tags: request.body.tags
});
post.save( function( err ) {
if( !err ) {
return console.log( 'Post saved');
} else {
console.log( err );
}
});
count++;
return response.send(post);
});
_id를 여러 가지 방법으로 설정하려고 했지만, 제게 효과가 없습니다.다음은 최근 오류입니다.
{ message: 'Cast to ObjectId failed for value "16" at path "_id"',
name: 'CastError',
type: 'ObjectId',
value: 16,
path: '_id' }
무슨 일이 일어나고 있는지 안다면, 저에게 알려주세요.
다음 중 하나를 선언해야 합니다._id스키마의 일부로 속성을 지정하거나 사용합니다._id옵션 및 설정false(사용 중입니다.id캐스트할 가상 게터를 생성하는 옵션_id문자열로, 그러나 여전히 생성되었습니다._idObjectID 속성이므로 캐스팅 오류가 발생합니다.
그럼 다음 중 하나는?
var Post = new mongoose.Schema({
_id: Number,
title: String,
content: String,
tags: [ String ]
});
또는 다음과 같습니다.
var Post = new mongoose.Schema({
title: String,
content: String,
tags: [ String ]
}, { _id: false });
@robertklep의 코드의 첫 번째 부분은 나에게 작동하지 않는다(몽구스 4), 또한 비활성화해야 합니다._id
var Post = new mongoose.Schema({
_id: Number,
title: String,
content: String,
tags: [ String ]
}, { _id: false });
그리고 이것은 나에게 효과가 있습니다.
mongoose에서 custom_id를 생성하고 해당 ID를 mongo_id로 저장합니다.이렇게 문서를 저장하기 전에 mongo_id를 사용합니다.
const mongoose = require('mongoose');
const Post = new mongoose.Schema({
title: String,
content: String,
tags: [ String ]
}, { _id: false });
// request body to save
let post = new PostModel({
_id: new mongoose.Types.ObjectId().toHexString(), //5cd5308e695db945d3cc81a9
title: request.body.title,
content: request.body.content,
tags: request.body.tags
});
post.save();
스키마에 대한 새 데이터를 저장할 때 사용할 수 있습니다.프로젝트에서 아래의 정확한 코드를 사용했습니다.
new User(
{
email: thePendingUser.email,
first_name: first_name || thePendingUser.first_name,
last_name: last_name || thePendingUser.last_name,
sdgUser: thePendingUser.sdgUser,
sdgStatus: "active",
createdAt: thePendingUser.createdAt,
_id: thePendingUser._id,
},
{ _id: thePendingUser._id }
)
언급URL : https://stackoverflow.com/questions/19760829/how-to-set-id-to-db-document-in-mongoose
반응형
'programing' 카테고리의 다른 글
| Ruby 배열을 X 요소의 일부로 분할(청크)하는 방법은 무엇입니까? (0) | 2023.05.27 |
|---|---|
| npm은 패키지에 종속성별로 개인 github 저장소를 설치합니다.제이손 (0) | 2023.05.27 |
| 열 순서가 절별 그룹에서 중요합니까? (0) | 2023.05.27 |
| SQL Server 인덱스 이름 지정 규칙 (0) | 2023.05.27 |
| Visual Studio Code에서 서로 다른 분기를 비교하는 방법 (0) | 2023.05.27 |