mongoose – 创build和插入数据到新的集合

现在我是MEAN.io的初学者。 我正在使用mongoose将数据插入到数据库。 我遵循这里的代码。

在我的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的错误TypeError: Cannot call method 'insert' of undefined

但是,如果我把dbCollection.people.insert ,它工作正常。 任何人都可以告诉我如何创build新的收集和插入数据。

我做了这些更改来解决问题:

我没有在mongo shell中创build集合,而是将下面的代码放在module.factory.js

 this.Person = mongoose.model('Person',PersonSchema); this.Person.db.collection("user", { .... } );