我有一个节点js程序,我试图通过我的API向集合中插入一个新文档:
router.post('/add', function(req, res) {
var apple = {
name: req.body.name,
ip: req.body.ip
}
serverSchema.insert(apple, function(err, result) {
if (err) {
console.log(err);
} else {
console.log('added');
}
});
});
架构如下所示:
var serverSchema = new mongoose.Schema({
// unique + required do not allow duplicates in the dbs
name: {
type: String,
unique: true,
required: true
},
ip: {
type: String,
unique: true,
required: true
}
});
module.exports = mongoose.model('serverSchema', serverSchema);
但是,当我尝试添加此项时,我会收到以下错误:
TypeError: Object function model(doc, fields, skipId) {
if (!(this instanceof model)) {
return new model(doc, fields, skipId);
}
Model.call(this, doc, fields, skipId);
} has no method 'insert'
知道为什么会这样吗?
* dbs连接已打开
由于
答案 0 :(得分:0)
您似乎错误地使用了serverSchema
。 insert
没有mongoose.schema
方法。
架构文件如下所示:
var mongoose = require("mongoose");
var db = mongoose.connect('mongodb://000.0.0.1/test');
var serverSchema = new mongoose.Schema({
name: {
type: String,
unique: true,
required: true
},
ip: {
type: String,
unique: true,
required: true
}
});
module.exports = db.model('server', serverSchema)
API文件如下所示:
router.post('/add', function(req, res) {
//require mongoose model defines in model/serverSchema.js
var aServer = require("./model/serverSchema");
var apple = new aServer({name: "Honeycrisp", ip: "red"});
post.save(function(err) {
if (err) {
return err;
} else {
console.log('added');
}
});
});