Home Unable to get records by findOne() if I use custom id for inserting records in mongoDB
Reply: 1

Unable to get records by findOne() if I use custom id for inserting records in mongoDB

CodeHunter
1#
CodeHunter Published in 2018-02-13 18:48:36Z

So I inserted records in my mongoDB schema using

> db.records.insert( { _id: "6", "name": "Ashish", "City": "Dallas" } )

When I am trying to fetch them using http://localhost:6001/api/employees/ I get below response:

[{"name":"Chris","City":"New York"},{"name":"Ashish","City":"Dallas"},{"_id":"5a832ac77ffc3c4e149be718","name":"Sarthak","City":"New York"},{"_id":"5a833071e0184c27ff514c6f","number":"6","name":"Ashish","City":"Dallas"}]

Notice how certain records have _id field and others do not. The records which do not have _id fields are the ones inserted using db.records.insert() command. Also, if I try to fetch those custom entered records, I get error as below:

On trying to fetch records with _id=6 using http://localhost:6001/api/employees/6 I get :

{"message":"Cast to ObjectId failed for value \"6\" at path \"_id\" for model \"records\"","name":"CastError","stringValue":"\"6\"","kind":"ObjectId","value":"6","path":"_id"}

as error response. I am using below code in my app.js to fetch the records:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/testing');
var Employee = mongoose.model('records',mongoose.Schema({
    name:String,
    City:String,

}));

var cfenv = require("cfenv");
var appEnv = cfenv.getAppEnv();
var port = appEnv.port || 6016;

app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.use(express.static(__dirname));

app.get('/api/employees',function(req,res){
    Employee.find(function(err,employees){
        if(err)
            return res.send(err);
        return res.json(employees);
    });
});

app.get('/api/employees/:id',function(req,res){
    Employee.findOne({_id: req.params.id},function(err,employees){
        if(err)
            return res.send(err);
        return res.json(employees);
    });
});

app.listen(port, function() {   
    console.log('server starting on ' + port);
});

Fields in the db as shown in compass tool:

Any idea?

fingeron
2#
fingeron Reply to 2018-02-13 19:48:57Z

The mongoose library is by default attempting to convert all _id values into mongoose.Types.ObjectId. It appears to ignore the value if conversion fails. In your situation, what you can probably be safest with is define to mongoose how to treat the _id fields in the schema.

var Employee = mongoose.model('records',mongoose.Schema({
    _id: String,
    name:String,
    City:String,

}));
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.424177 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO