Mongoose - create and insert data into a new collection

Now I am new to MEAN.io. I use mongooseto insert data into a database. And I follow the code here.

In my 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();

AT 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;

To enter data:

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');
        });
    });
});

It gives an error TypeError: Cannot call method 'insert' of undefined

But if I put it dbCollection.people.insert, it works great. Can someone tell me how to create a new collection and insert data into it.

+4
source share
1 answer

I made these changes to solve the problem:

Instead of creating a collection in the mongo shell, I put the following code in module.factory.js

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

All Articles