programing

스키마를 정의하지 않고 Mongoose를 사용하는 방법은 무엇입니까?

luckcodes 2023. 2. 11. 23:41

스키마를 정의하지 않고 Mongoose를 사용하는 방법은 무엇입니까?

이전 버전의 Mongoose(node.js의 경우)에서는 스키마를 정의하지 않고 사용할 수 있는 옵션이 있었습니다.

var collection = mongoose.noSchema(db, "User");

그러나 현재 버전에서는 "noSchema" 기능이 제거되었습니다.스키마가 자주 변경되기 때문에 정의된 스키마에 맞지 않습니다.mongoose에서 스키마리스 모델을 사용할 수 있는 새로운 방법이 있습니까?

이게 몽구스 스트릭트를 찾는 것 같아

옵션: strict

strict 옵션(기본적으로 유효)을 사용하면 스키마에서 지정되지 않은 모델인스턴스에 추가된 값이 db에 저장되지 않습니다.

주의: 정당한 이유가 없는 한 false로 설정하지 마십시오.

    var thingSchema = new Schema({..}, { strict: false });
    var Thing = mongoose.model('Thing', thingSchema);
    var thing = new Thing({ iAmNotInTheSchema: true });
    thing.save() // iAmNotInTheSchema is now saved to the db!!

실제로 '혼재' (Schema.Types.Mixed)모드는 Mongoose에서 정확히 그렇게 하고 있는 것 같습니다.

스키마가 필요 없는 자유형 JS 오브젝트를 사용할 수 있기 때문에 무엇이든 할 수 있습니다.그 후에 수동으로 그 오브젝트를 저장해야 할 것 같지만, 공정한 트레이드오프인 것 같습니다.

혼재

"무엇이든 사용할 수 있는" Schema Type의 유연성은 유지보수가 더 어렵다는 단점이 있습니다.혼합은 다음 중 하나를 통해 제공됩니다.Schema.Types.Mixed또는 빈 오브젝트 리터럴을 전달함으로써 이루어집니다.다음은 동등합니다.

var Any = new Schema({ any: {} });
var Any = new Schema({ any: Schema.Types.Mixed });

스키마가 없는 타입이기 때문에 원하는 다른 타입으로 값을 변경할 수 있지만 Mongoose는 이러한 변경을 자동 검출하여 저장하는 기능을 상실합니다.Mongoose에게 Mixed type 값이 변경되었음을 '알리려면'.markModified(path)문서가 방금 변경한 혼합 유형으로 경로를 전달하는 방법.

person.anything = { x: [3, 4, { y: "changed" }] };
person.markModified('anything');
person.save(); // anything will now get saved

크리스, 몽구스 개발 중에 스키마가 자주 바뀌기 때문에 mongoose도 같은 문제가 있었습니다.Mongous는 내가 Mongoose의 단순함을 가질 수 있게 해주었고, 동시에 나의 스키마를 느슨하게 정의하고 바꿀 수 있게 해주었다.표준 JavaScript 객체를 구축하여 데이터베이스에 저장하는 것을 선택했습니다.

function User(user){
  this.name = user.name
, this.age = user.age
}

app.post('save/user', function(req,res,next){
  var u = new User(req.body)
  db('mydb.users').save(u)
  res.send(200)
  // that's it! You've saved a user
});

Mongoose보다 훨씬 간단하지만, "Pre"와 같은 멋진 미들웨어를 놓치지는 않을 것입니다.하지만 난 그 어떤 것도 필요없었다.도움이 되었으면 좋겠어!!!

자세한 내용은 다음과 같습니다.[http://www.meanstack.site/http/01/save-data-to-mongodb-without-http.site][1]

    const express = require('express')()
    const mongoose = require('mongoose')
    const bodyParser = require('body-parser')
    const Schema = mongoose.Schema

    express.post('/', async (req, res) => {
        // strict false will allow you to save document which is coming from the req.body
        const testCollectionSchema = new Schema({}, { strict: false })
        const TestCollection = mongoose.model('test_collection', testCollectionSchema)
        let body = req.body
        const testCollectionData = new TestCollection(body)
        await testCollectionData.save()
        return res.send({
            "msg": "Data Saved Successfully"
        })
    })


  [1]: https://www.meanstack.site/2020/01/save-data-to-mongodb-without-defining.html

★★★★★★{ strict: false }파라미터는 작성과 갱신 모두에서 기능합니다.

더 이상 가능하지 않아요.

Mongoose는 스키마 및 노드 드라이버가 있는 컬렉션과 함께 사용하거나 이러한 스키마가 없는 드라이버에 대해 다른 mongo 모듈을 사용할 수 있습니다.

https://groups.google.com/forum/ #!msg/mongoose-orm/Bj9KTjI0NAQ/qSojYmoDwDYJ

언급URL : https://stackoverflow.com/questions/5370846/how-do-you-use-mongoose-without-defining-a-schema