kisor kisor - 6 months ago 13
Node.js Question

inserting document of collections to another collections in mongodb

i have two different collection of documents in a mongodb database. in my recruits collection i have plenty of documents. and i want to add the document from recruit collections to employee collections
here is part of my code

function register(){
$http({
url:'/employee',
method:'post',
data:data // data is what i get from findById query.
}).then(function(result){
vm.cancel();
vm.toast();
},function(err){
console.log(err);
})


here data is what i get from findById from recruits collections. now same data i want to store in employees collection.i tried so:

var emp = require('../models/employees.js');
router.post('/',function(req,res){
console.log(req.body);
var register = new emp(req.body);
//console.log(register);
register.save(function(err, respond) {
if (err) {
throw err;
} else {
res.json(respond);
}
})
});


i think its fine with the code my console shows me

MongoError: E11000 duplicate key error index: humanResource.employees.$_id_ dup
key: { : ObjectId('57395146b4c73790056a3770') }


any one suggest me how to insert such document in another collections.

Answer

You error is saying that the document you are creating has a _id which already exists in employees collection. The problem is that you are receiving recruit data and directly passing it to the employees collection along with the _id which is passed from the recruit. You should try copying the data but excluding the _id field. Mongo will automatically generate a _id for your employees collection. something like this,

var emp = require('../models/employees.js');
router.post('/',function(req,res){
      console.log(req.body);
       delete req.body._id;
      var register = new emp(req.body);
      register.save(function(err, respond) {
if (err) {
      throw err;
} else {
     res.json(respond);
}
});
Comments