node.js - 从 node.js 在 mongolab mongodb 数据库中创建集合模式

标签 node.js mongodb mongoose mlab

我是 node.js 和 mongodb 的新手。

我正在尝试使用以下代码从 node.js 应用程序中为 mongolab mongodb 数据库中的用户集合创建模式。代码似乎没有失败(至少,我没有收到错误消息),但我也没有看到任何成功的迹象。也就是说,当我去 mongolab 并查看我的数据库时,我没有看到任何模式已创建 - https://dzwonsemrish7.cloudfront.net/items/01263Y1c312s233V0R17/mongodb-schema.png?v=7fdc20e3 .

谁能解释我可能做错了什么,或者我如何验证我的代码是否成功以及实际上是为我的集合创建了一个架构?

// file: app.js

var express = require('express'),
    http = require('http'),
    mongoose = require('mongoose');

var app = express(),
    port = 3000;

// Connect to database in the cloud (mongolab)
mongoose.connect('mongodb://username:password@ds041344.mongolab.com:41344/stockmarket');

// Create a schema for User collection
mongoose.connection.on('open', function () {
    console.log(">>> Connected!");

    var UserSchema = new mongoose.Schema({
        username: {type: String, unique: true},
        password: String
    });

    var UserModel = mongoose.model('User', UserSchema);
});

app.get('/', function(req, res){
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello, World!\n');
});

http.createServer(app).listen(port, function(){
  console.log("Express server listening on port " + port + " ...");
});

最佳答案

您必须先插入一个文档。模式在 mongodb 中没有明确定义。插入文档后,将自动创建集合,您将在 mongolab 控制台中看到它。

示例来自 http://mongoosejs.com/

var mongoose = require('mongoose');
var db = mongoose.createConnection('localhost', 'test');

var schema = mongoose.Schema({ name: 'string' });
var Cat = db.model('Cat', schema);

var kitty = new Cat({ name: 'Zildjian' });
kitty.save(function (err) {
  if (err) // ...
  console.log('meow');
});

在上面的保存调用之后将创建集合

关于node.js - 从 node.js 在 mongolab mongodb 数据库中创建集合模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13322744/

相关文章:

node.js - 带有 $project 的 mongodb 聚合有条件地排除一个字段

node.js - 使用 eureka-js-client Node 库发现实例

javascript - Passport.js `isAuthenticated()` 不一致的行为;应该为真时为假

javascript - 在二维数组中查找精确值

javascript - 我怎样才能在 Mongo Shell 中将其作为一个命令运行

javascript - ( Node :9263) UnhandledPromiseRejectionWarning: ValidationError: ideas validation failed: imageUrl: Path `imageUrl` is required

node.js - windows azure 中的 Svgs 和其他 mime 类型

java - 如何使用 mongodb api Java 检索集合名称?

javascript - 模式中的 Mongoose 模式

node.js - 如何在 KeystoneJS 中创建唯一键