Node.js + Mongoose中的基本build模

我坚持开发一个node.js应用程序。 我试图build立一个音阶,它有一个名字和一些相关的音符:

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来创build新的条目,但是有没有我必须把它放在节点应用程序的特定部分? 是否有一个最佳的使用方法? 我做错了吗?

我在这里相当困惑,但感觉好像我几乎掌握了它的工作方式。 有人能指出我正确的方向吗?

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

  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

你可能想看看.create()一个mongoose函数 。

我不确定这是否是唯一的方法,但是您可能需要添加类似的内容

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

那么你可以做一些类似的事情

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

在你的代码的另一部分,当你想要一个新的规模。

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