【发布时间】:2015-03-22 01:06:23
【问题描述】:
大家好,这是我第一次在这里提问,
我是 MEAN 堆栈的新手,现在我正在尝试使用它开发应用程序。据我了解,在 mongodb 中,Schema(数据库)可以有一个或多个集合(表(?)),当我使用 mongoose 时,我定义了一个 Song 模型和一个 Artist 模型:
对于歌曲:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var songSchema = new Schema({
songName: { type: String },
songArtist: [{type : Schema.Types.ObjectId, ref : 'Artist'}]
});
module.exports = mongoose.model('Song', songSchema);
艺术家:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var artistSchema = new Schema({
artistName: { type: String }
});
module.exports = mongoose.model('Artist', artistSchema);
我的 app.js 看起来像这样:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/song', function(err, res) {
if(err) throw err;
console.log('Connected to Database');
});
var models = require('./models/song')(app, mongoose);
据我了解和看到的问题是,我正在创建 2 个数据库/模式,而我想创建一个数据库/模式并在其中包含这两个集合:
SongDatabase:
--- Song
--- Artist
在这种情况下,我应该如何使用我的 mongoose 模型/控制器和我的 app.js 执行此操作?在此先感谢:)
【问题讨论】:
-
您只需要在您的应用程序中发出
mongoose.connect一次,并且“数据库”在连接字符串中定义。除非您特别说明,否则所有集合都将在该数据库中创建。您似乎在这里混淆了术语。我建议先做一些 mongoose 和 MongoDB 教程以正确理解。易于搜索。 -
我已经搜索了几个教程,但它们都只使用一个连接,你能提供一个看起来像我想做的事情吗? (1 db,2 个集合)
标签: node.js mongodb collections mongoose schema