[英]Mongoose/MongoDB Create Collection if not exists based on Schema
I want to create a collection if it doesnt exists and fill it with the preset defaults from a Mongoose Schema.如果集合不存在,我想创建一个集合,并使用 Mongoose Schema 中的预设默认值填充它。
The idea is to create AND populate a Database on first run or do nothing if it already exists.这个想法是在第一次运行时创建并填充数据库,或者如果它已经存在则什么都不做。
I have a working solutions but I was wondering if there is a better way to do it, here's my solution:我有一个可行的解决方案,但我想知道是否有更好的方法来做到这一点,这是我的解决方案:
settings.js (Schema)
var mongoose = require('mongoose');
// define the schema for our account data
var settingsSchema = mongoose.Schema({
cmdPrefix : {type:String, default: '!'},
fontColor: {type: String, default:'<font color=\'#89D2E8\'>'},
loggedOn: {type:Date, default:Date.now}
},{timestamps : true});
// methods ======================
// create the model and expose it to our app
module.exports = mongoose.model('Settings', settingsSchema);
start.js(Start File)
const Settings = require('./config/models/settings.js');
...
mongoose.connect('mongodb://localhost/testdb'); // connect to our database
settingsExists();
...
function settingsExists() {
Settings.find({},function(err, result) {
if (result.length > 0) {
console.log('found ' + result);
} else {
console.log('not found, creating');
let newSettings = new Settings({});
newSettings.save();
}
});
}
Buddy Do Like This哥们这样做
if (!mongoose.models.Settings) {
mongoose.model('Settings', settingsSchema);
}
module.exports = moongose;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.