node.js 如何在不定义模式的情况下使用 Mongoose?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5370846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you use Mongoose without defining a schema?
提问by Christopher Tarquini
In previous versions of Mongoose (for node.js) there was an option to use it without defining a schema
在以前版本的 Mongoose(用于 node.js)中有一个选项可以在不定义架构的情况下使用它
var collection = mongoose.noSchema(db, "User");
But in the current version the "noSchema" function has been removed. My schemas are likely to change often and really don't fit in with a defined schema so is there a new way to use schema-less models in mongoose?
但在当前版本中,“noSchema”功能已被删除。我的模式可能会经常更改,并且真的不适合已定义的模式,那么是否有一种新方法可以在 mongoose 中使用无模式模型?
回答by Jonathan P. Diaz
I think this is what are you looking for Mongoose Strict
我想这就是你要找的Mongoose Strict
option: strict
选项:严格
The strict option, (enabled by default), ensures that values added to our model instance that were not specified in our schema do not get saved to the db.
严格选项(默认启用)可确保添加到我们模型实例中但未在我们的架构中指定的值不会保存到数据库中。
Note: Do not set to false unless you have good reason.
注意:除非有充分的理由,否则不要设置为 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!!
回答by kwhitley
Actually "Mixed" (Schema.Types.Mixed) mode appears to do exactly that in Mongoose...
实际上,“混合” ( Schema.Types.Mixed) 模式似乎在猫鼬中完全相同......
it accepts a schema-less, freeform JS object- so whatever you can throw at it. It seems you have to trigger saves on that object manually afterwards, but it seems like a fair tradeoff.
它接受一个无模式的、自由形式的 JS 对象——所以无论你可以扔给它什么。之后似乎您必须手动触发对该对象的保存,但这似乎是一个公平的权衡。
Mixed
An "anything goes" SchemaType, its flexibility comes at a trade-off of it being harder to maintain. Mixed is available either through
Schema.Types.Mixedor by passing an empty object literal. The following are equivalent:var Any = new Schema({ any: {} }); var Any = new Schema({ any: Schema.Types.Mixed });Since it is a schema-less type, you can change the value to anything else you like, but Mongoose loses the ability to auto detect and save those changes. To "tell" Mongoose that the value of a Mixed type has changed, call the
.markModified(path)method of the document passing the path to the Mixed type you just changed.person.anything = { x: [3, 4, { y: "changed" }] }; person.markModified('anything'); person.save(); // anything will now get saved
混合
“任何事情都可以”的 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
回答by Hacknightly
Hey Chris, take a look at Mongous. I was having the same issue with mongoose, as my Schemas change extremely frequently right now in development. Mongous allowed me to have the simplicity of Mongoose, while being able to loosely define and change my 'schemas'. I chose to simply build out standard JavaScript objects and store them in the database like so
嘿 Chris,看看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
});
Far more simple than Mongoose, although I do believe you miss out on some cool middleware stuff like "pre". I didn't need any of that though. Hope this helps!!!
远比 Mongoose 简单,尽管我相信你会错过一些很酷的中间件,比如“pre”。不过,我不需要任何这些。希望这可以帮助!!!
回答by Vipul Panchal
Here is the details description: [https://www.meanstack.site/2020/01/save-data-to-mongodb-without-defining.html][1]
以下是详细说明:[ 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
回答by masylum
Its not possible anymore.
它不再可能了。
You can use Mongoose with the collections that have schema and the node driver or another mongo module for those schemaless ones.
您可以将 Mongoose 与具有架构和节点驱动程序的集合或其他 mongo 模块一起用于那些无架构的集合。
https://groups.google.com/forum/#!msg/mongoose-orm/Bj9KTjI0NAQ/qSojYmoDwDYJ
https://groups.google.com/forum/#!msg/mongoose-orm/Bj9KTjI0NAQ/qSojYmoDwDYJ

