Be lazy, Be crazy

[mongoose Array update 예시] 본문

카테고리 없음

[mongoose Array update 예시]

정신이 많이없는 개발자 2022. 1. 27. 22:44
728x90
반응형
안녕하세요 mongoose를 사용하면서 배열에 있는 데이터를 수정하는데 있어 어려움이있었습니다.
doc를 참조해서 문제를 해결 했으며 저와 같은 어려움을 겪는 분들에게 조금이나마 도움이 되고자 글을 작성합니다.

 

https://docs.mongodb.com/manual/reference/operator/update/positional/   mongoDB.DOC

 

$ (update) — MongoDB Manual

Docs Home → MongoDB Manual$The positional $ operator identifies an element in an array to update without explicitly specifying the position of the element in the array.DisambiguationTo project, or return, an array element from a read operation, see the $

docs.mongodb.com

밑에 코드는 node.js에서 스키마를 작성했습니다. 

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// tokenId, nftName, imgUrl, description, 발행자:(주식회사Watto), tokenUrl
// 좋아요, 즐겨찾기 칼럼 추가하기
const nftSchema = mongoose.Schema({
	address: {
		type: String,
	},
	tokenId: {
		type: Number,
	},
	contentTitle: {
		type: String,
		maxlength: 50,
	},
	nftName: {
		type: String,
		maxlength: 50,
	},
	description: {
		type: String,
	},
	imgUri: {
		type: String,
	},
	tokenUrl: {
		type: String,
	},
	price: {
		type: Number,
	},
	sale: {
		type: Boolean,
		default: false,
	},
	type: {
		type: String,
		default: '',
	},
	spender: {
		type: String,
		default:'',
	},
	bids: {
		type : Array,
		default:[],
	},
});

const Nft = mongoose.model('Nft', nftSchema);

module.exports = { Nft };

//

 

Nft.findOneAndUpdate(
			{ tokenId : tokenId },		
			{ $push: { bids:bid}},
			(err, result) => {
				console.log('autcion is normal, Do not Worry');
				res.json({
					success: true,
					detail: 'success set highstbid',
				});
				if (err) console.log(err);
			}
		)

몽고디비 배열타입으로 되어있는 bids에 push하는 쿼리문입니다.

쿼리문 실행 결과

이제 bids라는 배열 안에 있는 biddest를 false로 만들어 봅시다.


// 비동기로 해서 inf라는 변수에 결과값을 받았습니다. 
const inf = await Nft.updateOne({ tokenId, "bids.bidAddress": owner }, { $set: {"bids.$.biddest":true}}).exec();
		console.log(inf);
        
		
        
        
        
        
        
        
        
  ///////터미널에 발생되는 결과 값
        {
[0]   acknowledged: true,
[0]   modifiedCount: 1,
[0]   upsertedId: null,
[0]   upsertedCount: 0,
[0]   matchedCount: 1
[0] }​

변경된 결과 값 확인
반응형
Comments