블로그
전체 3#카테고리
- 웹 개발
- 백엔드
#태그
- mongoose
- node.js
2022. 12. 15.
0
노드 리액트 기초 강의 #13 mongoose methods statics 차이
in mongoose, I made method using methods and statics. What is the difference? In Mongoose, the methods object on a schema is used to add instance methods, which are available on all documents of that schema. In contrast, the statics object is used to add static methods, which are available on the model itself.Here's an example of how you might use these two properties to add methods to a schema:const mongoose = require('mongoose'); const schema = new mongoose.Schema({ name: String, age: Number }); // Add an instance method schema.methods.greet = function() { console.log(`Hello, my name is ${this.name}`); } // Add a static method schema.statics.findByName = function(name) { return this.find({ name }); } const Model = mongoose.model('Model', schema); const instance = new Model({ name: 'John', age: 20 }); // Use the instance method instance.greet(); // Output: "Hello, my name is John" // Use the static method const john = Model.findByName('John'); As you can see in the example, instance methods are called on individual documents, while static methods are called on the model itself. This is the main difference between the methods and statics properties in Mongoose. when do i use them? You would use instance methods when you want to add a method that will be available on all documents of a certain schema. For example, you might add an instance method to a User schema that allows you to generate a password reset token for a user. This method would be called on an individual user document, and would only be available for that user.You would use static methods when you want to add a method that will be available on the model itself, rather than on individual documents. For example, you might add a static method to a User schema that allows you to find all users with a certain name. This method would be called on the User model, and would return an array of all matching users.In general, you would use instance methods when you want to operate on a single document, and static methods when you want to operate on a collection of documents or the model itself.
웹 개발
・
mongoose
2022. 12. 13.
0
노드 리액트 기초 강의 #12 토큰 생성 with jsonwebtoken
userSchema.methods.generateToken = async function(cb) { // jsonWebToken으로 토큰 생성 const user = this; const tokenPayload = { _id: user._id }; const token = jwt.sign(tokenPayload, 'secreteToken'); // 이부분을 (user._id.toHexString(), 'secreteToken')으로 만들었다. this.token = token; try { await user.save(); cb(null, user); } catch (err) { cb(err); } }; 영상에서 user._id만 했을 경우 저 부분이 plain object가 아니라서 오류가 났다. 따라서 hexString으로 만드는 것도 좋지만 객체로 만들어서 적용한느 것도 좋아보인다.
웹 개발
2022. 12. 11.
0
노드 리액트 기초 강의 #11 로그인 기능 with Bcrypt (1)
User.jsuserSchema.pre('save', function (next) { var user = this //비밀번호를 암호화 한다. if (user.isModified('password')) { // 기존 데이터의 비밀번호를 바꿀 때는 적용 안된다. const saltRounds = 10; bcrypt.hash(user.password, saltRounds, function (err, hash) { if (err) return next(err) user.password = hash next() // 이곳에 붙으면 암호화가 된다 }); next() // 이곳에 붙으면 암호화가 안된 비밀번호가 디비에 저장 된다 } else { return next() } })코드의 순서를 콘솔로그로 확인하니 bcrypt.hash 이 부분이 index.js의 save부분보다 나중에 실행되었다. pre함수지만 pre하지 않은 부분이었다. 따라서 이 부분을 고쳐야 했다.나는 async/await로 고쳤다. 그러면 예상대로 코드가 진행된다.userSchema.pre('save', async function (next) { const user = this //비밀번호를 암호화 한다. if (user.isModified('password')) { const saltRounds = 10; const hash = await bcrypt.hash(user.password, saltRounds); user.password = hash return next() } else { return next() } })
백엔드
・
node.js