[英]Creating a collection schema in a mongolab mongodb database from node.js
I'm new to node.js and mongodb. 我是node.js和mongodb的新手。
I'm trying to create a schema for a User collection in a mongolab mongodb database from a node.js app with the code below. 我正在尝试使用以下代码从node.js应用程序在mongolab mongodb数据库中为User集合创建模式。 The code does not seem to be failing (at least, I get no error messages), but I don't see any indication that it is succeeding either.
代码似乎没有失败(至少,我没有得到错误消息),但我没有看到任何迹象表明它也成功了。 That is, when I go to mongolab and look at my database, I don't see that any schema was created - https://dzwonsemrish7.cloudfront.net/items/01263Y1c312s233V0R17/mongodb-schema.png?v=7fdc20e3 .
也就是说,当我去mongolab并查看我的数据库时,我没有看到任何架构被创建 - https://dzwonsemrish7.cloudfront.net/items/01263Y1c312s233V0R17/mongodb-schema.png?v=7fdc20e3 。
Can someone explain what I might be doing wrong, or how I can verify that my code succeeded and a schema was, in fact, created for my collection? 有人可以解释我可能做错了什么,或者我如何验证我的代码是否成功,并且实际上是为我的集合创建了一个模式?
// 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 + " ...");
});
You must insert a document first. 您必须先插入文档。 Schemas are not explicitly defined in mongodb.
模式没有在mongodb中明确定义。 Once you insert a document, the collection will automatically be created and you will see it in the mongolab console.
插入文档后,将自动创建该集合,您将在mongolab控制台中看到它。
Example from http://mongoosejs.com/ 来自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');
});
after the save call above the collection will be created 在上面的保存调用之后,将创建集合
Data in MongoDB has a flexible schema. MongoDB中的数据具有灵活的架构。 Documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection's documents may hold different types of data.
同一集合中的文档不需要具有相同的字段或结构集,集合文档中的公共字段可以包含不同类型的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.