programing

MongoDB 몽구스 사용 중지 경고

closeapi 2023. 5. 1. 21:24
반응형

MongoDB 몽구스 사용 중지 경고

를 사용하여 문서를 쿼리하는 동안collection.find콘솔에 다음 경고가 표시되기 시작했습니다.

사용 중지 경고: 컬렉션입니다.찾기 옵션 [fields]는 더 이상 사용되지 않으며 이후 버전에서 제거됩니다.

이 문제가 발생하는 이유와 해결 방법(가능한 대안)

편집: 쿼리가 추가됨

Session
        .find({ sessionCode: '18JANMON', completed: false })
        .limit(10)
        .sort({time: 1})
        .select({time: 1, sessionCode: 1});

Mongoose 버전 5.2.9

업데이트:

5.2.10은 릴리스되었으며 여기에서 다운로드할 수 있습니다.

문서에 대한 자세한 내용은 https://mongoosejs.com/docs/deprecations 페이지를 참조하십시오.

이 문제 및 해결 방법에 대한 자세한 내용은 https://github.com/Automattic/mongoose/issues/6880 을 참조하십시오.

원본 답변:

Mongoose 5.2.9 버전은 네이티브 mongodb 드라이버를 3.1.3으로 업그레이드했으며, 여기서 더 이상 사용되지 않는 네이티브 드라이버 메서드가 호출될 때 경고 메시지를 던지기 위한 변경 사항이 추가되었습니다.

fields 옵션이 더 이상 사용되지 않으며 다음으로 대체되었습니다.projection선택.

mongoose가 필드 옵션을 투영으로 대체하기 위해 변경할 때까지 기다려야 합니다.수정 프로그램은 5.2.10 릴리스로 예약되어 있습니다.

당분간은 5.2.8로 돌아가서 모든 사용 중지 경고를 표시할 수 있습니다.

npm install mongoose@5.2.8

다른 모든 사용되지 않는 경고의 경우 사례별로 접근해야 합니다.

다른 수집 방법을 사용할 때 다른 사용 중지 경고가 표시됩니다.

DeprecationWarning: collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.
DeprecationWarning: collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.
DeprecationWarning: collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.
DeprecationWarning: collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead.
DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.

모든.findOne*mongoose 쓰기 메서드는 기본적으로 mongodb 네이티브 드라이버에서 사용되지 않는 메서드를 사용합니다.

사용하다mongoose.set('useFindAndModify', false);몽구스에게 적절한 전화를 하게 하다findOne*method가 mongodb 네이티브 드라이버에 있습니다.

위해서remove그리고.update전화를 로 대체합니다.delete*그리고.update*각각의 방법.

위해서save전화를 로 대체합니다.insert*/update*각각의 방법.

사용하다mongoose.set('useCreateIndex', true);몽구스가 전화를 걸게 하다createIndexmethod가 mongodb 네이티브 드라이버에 있습니다.

mongoose.connect('your db url', {
  useCreateIndex: true,
  useNewUrlParser: true
})

또는

mongoose.set('useCreateIndex', true)
mongoose.connect('your db url', { useNewUrlParser: true })

버전 5.2.10으로 업그레이드한 후.아래 옵션 중 하나를 사용할 수 있습니다.

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/test', {

  useCreateIndex: true,
  useNewUrlParser: true

})
.then(() => console.log('connecting to database successful'))
.catch(err => console.error('could not connect to mongo DB', err));


or

const mongoose = require('mongoose');

mongoose.set('useCreateIndex', true);

mongoose.connect('mongodb://localhost/test',{

    useNewUrlParser: true

})
.then(() =>  console.log('connecting to database successful') )
.catch(err =>  console.error('could not connect to mongo DB', err) );

할 수 있습니다.npm install mongoose@5.2.8그러면 사용자가 사용 중지 경고를 표시하지 않는 이전 버전으로 돌아갈 수 있습니다.

이것은 2020년 4월에 저에게 효과가 있었습니다.

mongoose.connect(process.env.DATABASE_URL, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true
})

mongoose.connect('mongodb://localhost:27017/tablename',{ useUnifiedTopology: true, useNewUrlParser: true,useCreateIndex: true },()=>{ console.log(연결된 db) });

저는 현재 "mongoose@5.11.15"를 사용하고 있습니다. 당신은 이것을 사용하여 폐지 경고를 제거할 수 있습니다.

방법 1

mongoose.connect("Your DB address", {
useNewUrlParser: true,                       
useUnifiedTopology: true,                 
useCreateIndex: true               // to handle collection.ensureIndex is deprecated
});

방법 2

mongoose.connect("Your DB address", {
useNewUrlParser: true,                       
useUnifiedTopology: true,                 // other deprecation warnings            
});
mongoose.set("useCreateIndex", true);     // to handle collection.ensureIndex is deprecated

CLI에서 --no-decretion을 사용하여 사용 중지 경고를 무시할 수도 있습니다.

이 경고를 받았습니다. - (노드:108) [MONGODB DRIVER] 경고: collection.update는 더 이상 사용되지 않습니다.대신 updateOne, updateMany 또는 bulkWrite를 사용합니다. ---decrecription 없이 정상적으로 작동했습니다.

여기에서 설명서 확인 - https://nodejs.org/dist/latest-v10.x/docs/api/cli.html#cli_no_deprecation

데이터베이스 연결 중에 다음 옵션만 전달

예를 들어

const mongoose = require("mongoose");

mongoose.connect("uri",{ 
                       "useNewUrlParser": true,
                       "useUnifiedTopology": true, 
                       "useCreateIndex": true 
                       // other deprecations 
                       },(err)=>{
     // connection logging

});

mongoose.connect(process.env.DATABASE, {
 useNewUrlParser: true,
 useCreateIndex: true,
 useFindAndModify: false,
 useUnifiedTopology: true,
})
.then(() => {
 console.log("DB connected");
})
.catch((err) => console.log(`DB connection Err`, err));

여기서connectionStringDB 주소입니다.

mongoose
  .connect(connectionString, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
  })
  .then(
    app.listen(port, () => {
      console.log(`server started on port ${port}`);
    })
  )
  .catch((err) => console.log(err));

우리가 mongodb를 연결하기 위해 연결 요청을 할 때 우리는 그 콜백 함수에 키 값 쌍을 하나 더 추가하기만 하면 됩니다.

useCreateIndex:true

함수 내부에

mongoose.connect(config.DB_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useCreateIndex:true
}

몽구스 버전 6.8.0을 사용하고 있으며 이것은 저에게 효과가 있었습니다.

 //connect mongodb 
     mongoose.set('strictQuery', false);
     mongoose.connect('url',(err,db) => {

    if(err){
        console.log(`Database not connected :   ${err}`)
    }else{
        console.log('Database connected Successfully')
    }
})

mongodb 데이터베이스에 연결하는 동안 감가상각 오류가 발생한 경우, 다음과 같은 환경 변수 파일에 연결 문자열을 저장하는 경우

//database connection string saved to a env variable
DB='mongodb://127.0.0.1:27017/players'

일반적인 정의 방법 대신 실제 IP 주소를 사용합니다.

DB='mongodb://localhost/players'

그런 다음 사용할 수 있는 데이터베이스에 연결할 때 다음 코드를 사용합니다.

//requiring the database driver mongoose
const mongoose = require('mongoose');

//connecting to mongodb
mongoose.connect(process.env.DB)
.then(() => console.log('Connected to mongodb Database...'))
.catch((err) => console.error('Unable to connect to MongoDB...', err));

이것은 확실히 저에게 효과가 있었습니다.내 컴퓨터에서 로컬로 사용하고 있으므로 서버 기반 데이터베이스를 사용하는 경우 데이터베이스 연결 문자열이 나와 동일하지 않습니다.

언급URL : https://stackoverflow.com/questions/51916630/mongodb-mongoose-deprecation-warning

반응형