[英]Creating a collection schema in a mongolab mongodb database from node.js
我是node.js和mongodb的新手。
我正在嘗試使用以下代碼從node.js應用程序在mongolab mongodb數據庫中為User集合創建模式。 代碼似乎沒有失敗(至少,我沒有得到錯誤消息),但我沒有看到任何跡象表明它也成功了。 也就是說,當我去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控制台中看到它。
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');
});
在上面的保存調用之后,將創建集合
MongoDB中的數據具有靈活的架構。 同一集合中的文檔不需要具有相同的字段或結構集,集合文檔中的公共字段可以包含不同類型的數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.