Now I am a beginner in MEAN.io. I am using mongoose
to insert data to DB. And I follow the code from 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();
In 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;
For inserting 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 throws an error of TypeError: Cannot call method 'insert' of undefined
But if I put dbCollection.people.insert
, it works fine. Can anyone tell me how to create new collection and insert data into that.
In MongoDB, copyTo() method is used to copies all the documents from one collection(Source collection) to another collection(Target collection) using server-side JavaScript and if that other collection(Target collection) is not present then MongoDB creates a new collection with that name.
create does a . save for each document in the array, resulting in N database calls (where N is the number of documents in the array); Collection. insert performs one large database call.
To insert data into MongoDB collection, you need to use MongoDB's insert() or save() method.
I did these changes to solve the issue:
Instead of creating collection in mongo shell, I put the following code in module.factory.js
this.Person = mongoose.model('Person',PersonSchema);
this.Person.db.collection("user", { .... } );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With