웹/MongoDB

[mongoDB] 임베디드 스키마 안의 정보를 이용한 데이터 검색

ohojee 2023. 8. 18. 15:25

먼저 스키마를 보자면 아래와 같이 작성했다

const userSchema  = mongoose.Schema({
	_id: {
		type: String, 
		minlength: 2,
		maxlength: 20,
	},
	auth: {
		token: String,
		ttl: Number
	}
});

User 스키마에 있는 _id를 찾을 때는 아래의 방법으로 찾을 수 있었다

const result = await User.findOne({ _id });

하지만 내가 찾고 싶은건 임베디드 스키마 안에 있는 token이었고 위의 방법으로 작성한다면 튜플을 찾지 못했다

const user = await User.findOne({ 'auth.token': `${token}` });

그럴 때는 이렇게 User.findOne({ 'auth.token': `${token}` })를 이용하면 잘 찾아진다!

+
User.findOne({ 'auth.token': token })
이것도 가능하다

 
 
참고 자료
https://www.mongodb.com/docs/manual/tutorial/query-embedded-documents/

Query on Embedded/Nested Documents — MongoDB Manual

Docs Home → MongoDB Manual ➤ Use the Select your language drop-down menu in the upper-right to set the language of the following examples.For example, the following query selects all documents where the field size equals the document { h: 14, w: 21, uo

www.mongodb.com