Chr*_*ini 106 mongoose mongodb node.js
在早期版本的Mongoose(对于node.js)中,有一个选项可以在不定义模式的情况下使用它
var collection = mongoose.noSchema(db, "User");
但在当前版本中,"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!!
kwh*_*ley 55
实际上"混合"(Schema.Types.Mixed)模式似乎与Mongoose完全相同......
它接受一个无模式,自由形式的JS对象 - 所以你可以抛出它.看来你必须手动触发该对象的保存,但这似乎是一个公平的权衡.
杂
"任何事情都有"SchemaType,它的灵活性来自于它难以维护的权衡.混合可通过
Schema.Types.Mixed或通过传递空对象文字来获得.以下是等效的:Run Code Online (Sandbox Code Playgroud)var Any = new Schema({ any: {} }); var Any = new Schema({ any: Schema.Types.Mixed });由于它是无模式类型,因此您可以将值更改为您喜欢的任何其他值,但Mongoose无法自动检测并保存这些更改.要"告诉"Mongoose混合类型的值已更改,请调用
.markModified(path)文档的方法将路径传递给刚刚更改的混合类型.Run Code Online (Sandbox Code Playgroud)person.anything = { x: [3, 4, { y: "changed" }] }; person.markModified('anything'); person.save(); // anything will now get saved
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
});
比Mongoose简单得多,虽然我确实相信你错过了一些很酷的中间件,比如"pre".我不需要任何这些.希望这可以帮助!!!
小智 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
| 归档时间: | 
 | 
| 查看次数: | 56848 次 | 
| 最近记录: |