如何在不定义架构的情况下使用Mongoose?

Chr*_*ini 106 mongoose mongodb node.js

在早期版本的Mongoose(对于node.js)中,有一个选项可以在不定义模式的情况下使用它

var collection = mongoose.noSchema(db, "User");
Run Code Online (Sandbox Code Playgroud)

但在当前版本中,"noSchema"功能已被删除.我的模式可能经常更改,并且实际上不适合定义的模式,所以有没有一种在mongoose中使用无模式模型的新方法?

Jon*_*iaz 162

我想这就是你在寻找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!!
Run Code Online (Sandbox Code Playgroud)

  • PS:你必须做`thing.set(key,value)`因为`thing.key = value`不能用于这个方法,即它不会持久地改变到数据库中. (5认同)
  • 如果您使用此方法,则在检索文档时会遇到问题.在执行查找之后,doc.someProp doc.someProp将是未定义的,即使它实际上存在于对象上(console.log确认了这一点),这是因为mongoose定义了自己的getter,它们似乎只在你定义时才有效关于架构的支持 (4认同)
  • 你救了我的一天.我还发现这不能与#markMotified('<columnName>')一起使用 (2认同)
  • @ Melbourne2991这在一定程度上是对的,但是我发现了一种解决方法。您可以在检索到的文档上调用toJSON()方法,然后该方法将允许您使用常规的点表示法,例如doc.someProp。很抱歉回答这么旧的答案。只是想添加此内容,以防有人遇到相同的事情。[https://mongoosejs.com/docs/guide.html#toJSON](https://mongoosejs.com/docs/guide.html#toJSON) (2认同)

kwh*_*ley 55

实际上"混合"(Schema.Types.Mixed)模式似乎与Mongoose完全相同......

它接受一个无模式,自由形式的JS对象 - 所以你可以抛出它.看来你必须手动触发该对象的保存,但这似乎是一个公平的权衡.

"任何事情都有"SchemaType,它的灵活性来自于它难以维护的权衡.混合可通过 Schema.Types.Mixed或通过传递空对象文字来获得.以下是等效的:

var Any = new Schema({ any: {} });
var Any = new Schema({ any: Schema.Types.Mixed });
Run Code Online (Sandbox Code Playgroud)

由于它是无模式类型,因此您可以将值更改为您喜欢的任何其他值,但Mongoose无法自动检测并保存这些更改.要"告诉"Mongoose混合类型的值已更改,请调用.markModified(path)文档的方法将路径传递给刚刚更改的混合类型.

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

  • 但是这个结构将整个对象嵌在`any`字段下,所以它确实有一个模式.对OP的更好回答是使用`strict:false`作为[这个答案说.](http://stackoverflow.com/a/12389168/404699) (5认同)

Hac*_*tly 14

嘿克里斯,看看蒙古.我和mongoose有同样的问题,因为我的Schemas现在在开发中经常变化.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
});
Run Code Online (Sandbox Code Playgroud)

比Mongoose简单得多,虽然我确实相信你错过了一些很酷的中间件,比如"pre".我不需要任何这些.希望这可以帮助!!!

  • 我不认为这是对这个问题的真正答案,@ kwhitley对Mongoose有适当的答案. (4认同)

小智 5

以下是详细说明:[ 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
Run Code Online (Sandbox Code Playgroud)