2016-12-14 67 views
1

我一直在开发一个node.js应用程序。我想一个音阶,其中有一个名字和一些相关的注意事项型号:Node.js + Mongoose中的基本建模

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 

var scaleSchema = new Schema({ 
    name: String, 
    displayName: String, 
    notes: [{type: String}] 
}); 

module.exports = mongoose.model('Scale', scaleSchema); 

不过,我不知道如何“种子”,甚至进入这一模式。我想用一些只能装入一次的秤来填充它。我知道我可以要求这个模型,并使用new来创建新的条目,但是我必须将它放入节点应用程序的特定部分吗?是否有某种最佳实践可供使用?我做错了吗?

我在这里很困惑,但感觉好像我几乎掌握了它的工作原理。有人能指引我朝着正确的方向吗?

回答

2

您可以像创建对象一样创建新的数据库条目。这里是一个播种机类。

let mongoose = require('mongoose'), 
    User = require('../models/User'); 

    module.exports =() => { 

    User.find({}).exec((err, users) => { 
     if (err) { 
      console.log(err); 
     } else { 
      if (users.length == 0) { 
       let adminUser = new User(); 
       adminUser.username = 'admin'; 
       adminUser.password = adminUser.encryptPassword('admin'); 
       adminUser.roles = ['Admin']; 
       adminUser.save(); 

       console.log('users collection seeded') 
      } 
     } 
    }); 
}; 

然后在另一个文件中,你可以调用它,它会播种你的数据库。

let usersCollectionSeeder = require('./usersCollectionSeeder');  
usersCollectionSeeder(); 

希望这会有所帮助。

至于结构,我喜欢有一个名为“播种机”的文件夹。在那里我有一个名为databaseSeeder.js的文件,它需要像usersCollectionSeeder.js这样的其他播客,然后调用函数。

这是我喜欢使用的示例结构。

https://github.com/NikolayKolibarov/ExpressJS-Development

0

您可能想要查看.create()a mongoose function

我不知道这是否是这样做的唯一途径,但你可能要像

Scale.create({name: varThatHasValName, 
      displayName: varThatHasValdisplayName, 
      notes: varThatHasValnotes}, function (err,scale)); 

添加类似

var Scale = mongoose.model("Scale", scaleSchema); 
module.exports = Scale; //instead of what you currently have for you last line 

然后,你可以做一些事情在另一部分的代码,当你想创造一个新的规模。

我最近使用了一个类的节点和猫鼬,但我不是专家,但这可能是我会做的(如果我理解你的问题)。