hussain hussain - 2 months ago 10
Javascript Question

Issue in document insert using mongoose

I have schema created now i want to insert into mongodb collection, but its throwing error

diagramModel.insert
is not defined any idea what is implemented wrong ?

app.js

mongoose.connect('mongodb://localhost:27017/develop-modeler');
require('./server/api/diagram/diagram.model.js');
var diagramModel = mongoose.model('Diagram');
var newDiagram = {
"owner" : "sh529u",
"text" : "sco_poc.bpmn",
"users":["wp6307","kz323j","ew6980"],
"groups":[],
"string" : "test"
}
mongoose.connection.on('connected', function () {
diagramModel.insert(newDiagram,function(err,res){
if (err) { console.log(err);}
else {
diagramModel.find({}, function(err, data) { console.log(data);});
}
});

});


diagram.model.js

var DiagramSchema = new mongoose.Schema({
text: String,
owner: {type: String, ref:'User'},
groups: [{type: String, ref: 'Group'}],
users: [{type: String, ref: 'User'}],
string: String
});

mongoose.model('Diagram', DiagramSchema);

Answer

I think it's save not insert while saving records. That's why you are getting this error

 mongoose.connect('mongodb://localhost:27017/develop-modeler');
 var diagramModel = require('./server/api/diagram/diagram.model.js');
 var newDiagram = {
   "owner": "sh529u",
   "text": "sco_poc.bpmn",
   "users": ["wp6307", "kz323j", "ew6980"],
   "groups": [],
   "string": "test"
 }
 mongoose.connection.on('connected', function() {
   diagramModel.save(newDiagram, function(err, res) {
     if (err) {
       console.log(err);
     } else {
       diagramModel.find({}, function(err, data) {
         console.log(data);
       });
     }
   });
 });



var DiagramSchema = mongoose.Schema({
  text: String,
  owner: {type: String, ref:'User'},
  groups: [{type: String, ref: 'Group'}],
  users: [{type: String, ref: 'User'}],
  string: String
});
module.exports=mongoose.model('Diagram', DiagramSchema);