在以前版本的 Mongoose(用于 node.js)中,有一个选项可以在不定义模式的情况下使用它
var collection = mongoose.noSchema(db, "User");
但在当前版本中,“noSchema”功能已被删除。我的模式可能会经常更改,并且确实不适合已定义的模式,所以有没有一种新方法可以在猫鼬中使用无模式模型?
我想这就是你要找的Mongoose Strict
选项:严格
strict 选项(默认启用)确保添加到模型实例中但未在我们的模式中指定的值不会保存到数据库中。
注意:除非你有充分的理由,否则不要设置为 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 Mixed 类型的值已更改,请调用
.markModified(path)
文档的方法,将路径传递给刚刚更改的 Mixed 类型。person.anything = { x: [3, 4, { y: "changed" }] }; person.markModified('anything'); person.save(); // anything will now get saved
嘿,克里斯,看看Mongous。我对 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”。不过我不需要这些。希望这可以帮助!!!
以下是详细说明:[ 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
注意:该{ strict: false }
参数适用于创建和更新。
它已经不可能了。
您可以将 Mongoose 与具有模式的集合和节点驱动程序或其他 mongo 模块一起用于那些无模式的集合。
https://groups.google.com/forum/#!msg/mongoose-orm/Bj9KTjI0NAQ/qSojYmoDwDYJ