Hul*_*991 5 mongoose mongodb node.js express
现在我是 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();
Run Code Online (Sandbox Code Playgroud)
在 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;
Run Code Online (Sandbox Code Playgroud)
插入数据:
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');
});
});
});
Run Code Online (Sandbox Code Playgroud)
它抛出一个错误 TypeError: Cannot call method 'insert' of undefined
但如果我把dbCollection.people.insert它工作正常。谁能告诉我如何创建新集合并将数据插入其中。
我做了这些改变来解决这个问题:
我没有在 mongo shell 中创建集合,而是将以下代码放入 module.factory.js
this.Person = mongoose.model('Person',PersonSchema);
this.Person.db.collection("user", { .... } );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18454 次 |
| 最近记录: |