[mongodb] 스키마를 정의하지 않고 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 개체 당신이 그것에 던질 수있는 어떤 정도 -. 나중에 해당 개체에 대한 저장을 수동으로 트리거해야하는 것 같지만 공정한 트레이드 오프처럼 보입니다.

혼합

“무엇이든 간다”SchemaType의 유연성은 유지 관리가 더 어렵다는 단점이 있습니다. Mixed는 Schema.Types.Mixed빈 개체 리터럴을 통해 또는 전달하여 사용할 수 있습니다
. 다음은 동일합니다.

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

스키마가없는 유형이므로 원하는 다른 값으로 변경할 수 있지만 Mongoose는 이러한 변경 사항을 자동으로 감지하고 저장하는 기능을 잃습니다. 혼합 유형의 값이 변경되었음을 Mongoose에게 “알리려면” .markModified(path)방금 변경 한 혼합 유형에 대한 경로를 전달하는 문서 의 메소드를 호출하십시오 .

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

답변

안녕하세요, 크리스, 몽구스보세요 . 내 스키마가 개발 중에 매우 자주 변경되므로 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”와 같은 멋진 미들웨어를 놓친다고 생각합니다. 그래도 그 중 아무것도 필요하지 않았습니다. 도움이 되었기를 바랍니다!!!


답변

자세한 설명은 다음과 같습니다. [ https://www.meanstack.site/2020/01/save-data-to-mongodb-without-defining.html][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


답변

더 이상 가능하지 않습니다.

스키마가있는 컬렉션과 노드 드라이버 또는 스키마가없는 다른 mongo 모듈과 함께 Mongoose를 사용할 수 있습니다.

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


답변