[英]Create an independent user schema and also embed it in a message schema with Mongoose/MongoDB?
[英]Mongoose/MongoDB Create Collection if not exists based on Schema
如果集合不存在,我想創建一個集合,並使用 Mongoose Schema 中的預設默認值填充它。
這個想法是在第一次運行時創建並填充數據庫,或者如果它已經存在則什么都不做。
我有一個可行的解決方案,但我想知道是否有更好的方法來做到這一點,這是我的解決方案:
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();
}
});
}
哥們這樣做
if (!mongoose.models.Settings) {
mongoose.model('Settings', settingsSchema);
}
module.exports = moongose;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.