gpt4 book ai didi

node.js - Mongoose 模式和集合

转载 作者:太空宇宙 更新时间:2023-11-04 02:29:30 25 4
gpt4 key购买 nike

大家好,这是我第一次在这里提问,

我对 MEAN 堆栈非常陌生,现在我正在尝试使用它开发一个应用程序。据我了解,在 mongodb 中,模式(数据库)可以有一个或多个集合(表(?)),当我使用 mongoose 时,我定义一个歌曲模型和一个艺术家模型:

对于歌曲:

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 模型/ Controller 和我的 app.js 来做到这一点?预先感谢:)

最佳答案

通过查看this tutorial,我解决了所有疑问,正如您在这里所看到的,它们在一个数据库中实现了两个集合(我最初关心的问题)。连接到数据库并对所需的集合执行发布(在本例中为线程或发布)后,它将在 mongodb 中创建集合。

关于node.js - Mongoose 模式和集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28102348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com