4
現在我是MEAN.io中的初學者。我正在使用mongoose
將數據插入數據庫。於是我跟着從here.貓鼬 - 創建並將數據插入新集合
代碼在我app.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var Factory = require('./module.factory.js');
mongoose.connect('mongodb://localhost/angular');
var db = mongoose.connection;
var dbCollection = db.collections;
var factory = new Factory(Schema,mongoose);
factory.createSchemas();
在module.factory.js
var Factory = function(Schema,mongoose) {
this.Schema = Schema;
this.mongoose = mongoose;
this.Item = null;
this.createSchemas = function() {
var PersonSchema = new this.Schema({
first_name: String,
last_name: String,
city: String,
state: String
});
this.Person = mongoose.model('Person',PersonSchema);
};
this.getPerson = function(query,res) {
this.Person.find(query,function(error,output) {
res.json(output);
});
};
this.doLogin = function(query,res) {
this.Person.findOne(query,function(error,output) {
console.log(query);
res.json(output);
console.log(output);
});
};
};
module.exports = Factory;
插入數據:
app.post('/insert', function (req, res) {
req.addListener('data', function(message)
{
var command = JSON.parse(message);
var document = {first_name: command.fname,
last_name: command.lname,
city: command.city,
state: command.state};
dbCollection.user.insert(document,function(err, records){
res.send('Inserted');
});
});
});
它拋出的TypeError: Cannot call method 'insert' of undefined
但是,如果我把dbCollection.people.insert
,它工作正常。任何人都可以告訴我如何創建新的集合並在其中插入數據。
你有一個'user'集合。在控制檯中試試'show collections' – Sami 2014-10-08 07:35:49
我有'user'集合 – Hulk1991 2014-10-08 08:26:32