0
我一直在看Mongo DB,並努力獲得基本的權利。如何將文檔添加到MongoDB中的集合?
以下代碼似乎可以在Mac上運行,但在Windows上無法運行。我在Windows上沒有任何錯誤。如果我將用戶名/密碼更改爲不正確的組合,則會出現錯誤。當代碼沒有問題時,它根本不提供任何輸出,但根本沒有在數據庫中創建集合,但我期望有一個名爲things
的輸出。
我運行.\node_modules\mongoose\examples
中的示例代碼,它工作正常。我也試着將thing\index.js
中的代碼放在之內,以防止模塊導致問題,但行爲沒有變化。我究竟做錯了什麼?
這裏是我的示例代碼:
data.js
var loremIpsum = require('lorem-ipsum'),
mongoose = require('mongoose'),
Thing = require('./thing');
mongoose.connect('mongodb://username:[email protected]/Test', function (err) {
if (err) {
throw err;
}
createData();
})
function createData() {
Thing.model.create({
id: 1,
name: loremIpsum({
count: 5,
units: 'words',
format: 'plain'
}),
description: loremIpsum({
count: 100,
units: 'words',
format: 'plain'
})
}, function (err, thing) {
if (err) {
throw err;
}
console.log(thing.name);
});
mongoose.disconnect();
}
事/ index.js
var mongoose = require('mongoose');
var thingSchema = mongoose.Schema({
id: {
type: Number,
min: 1
},
date: {
type: Date,
default: Date.now
},
name: {
type: String,
trim: true
},
description: {
type: String,
trim: true
}
});
var thingModel = mongoose.model('Thing', thingSchema);
exports.schema = thingSchema;
exports.model = thingModel;