Mongoose - 创建数据并将数据插入新集合

时间:2014-10-08 06:58:59

标签: node.js mongodb express mongoose

现在我是MEAN.io的初学者。我正在使用mongoose向DB插入数据。我按照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,它就可以了。任何人都可以告诉我如何创建新的集合并将数据插入其中。

1 个答案:

答案 0 :(得分:4)

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

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

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