When using mongoose .
A representation of the _id
is usually in the form (received client side)
{ _id: { _bsontype: 'ObjectID', id: <Buffer 5a f1 8f 4b c7 17 0e 76 9a c0 97 aa> },
As you can see there's a buffer in there. The easiest way to convert it is just doing <obj>.toString()
or String(<obj>._id)
So for example
var mongoose = require('mongoose')
mongoose.connect("http://localhost/test")
var personSchema = new mongoose.Schema({ name: String })
var Person = mongoose.model("Person", personSchema)
var guy = new Person({ name: "someguy" })
Person.find().then((people) =>{
people.forEach(person => {
console.log(typeof person._id) //outputs object
typeof person._id == 'string'
? null
: sale._id = String(sale._id) // all _id s will be converted to strings
})
}).catch(err=>{ console.log("errored") })