Reputation: 872
Given the created document from the .save
method, or any other method that returns a document, how would I convert that document to a plain javascript object with primitive JSON types? I've tried .toJSON
and .toObject
but they both still maintain mongoose's ObjectId data type, when I want a string instead:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const Cat = mongoose.model('Cat', { name: String });
const kitty = new Cat({ name: 'aed' });
kitty.save()
.then(data => {
console.log(data.toObject()._id instanceof mongoose.Types.ObjectId)
console.log(data.toJSON()._id instanceof mongoose.Types.ObjectId)
console.log(data.toObject({ virtuals: true, getters: true })._id instanceof mongoose.Type.ObjectId)
console.log(data.toJSON({ virtuals: true, getters: true })._id instanceof mongoose.Types.ObjectId)
return data
})
.then(data => data.remove())
.catch(console.error);
true
true
true
true
I know I can use .lean()
, but I specifically need to the document as well as its plain object version
Thanks in advance
Upvotes: 1
Views: 4134
Reputation: 17858
You can first use toObject
, then JSON.stringify
, and then JSON.parse
.
router.post("/cat", (req, res) => {
const kitty = new Cat({ name: "Masha" });
kitty.save().then(data => {
const obj = data.toObject();
const str = JSON.stringify(obj);
const json = JSON.parse(str);
console.log(typeof json._id);
res.send(data);
});
});
The result of console.log(typeof json._id)
will be string
.
Also to remove version key, we can apply versionKey
false option in the schema definition.
const mongoose = require("mongoose");
const catSchema = new mongoose.Schema({ name: String }, { versionKey: false });
const Cat = mongoose.model("Cat", catSchema);
module.exports = Cat;
Upvotes: 2
Reputation: 144
You can spread that document (see example below). But in that case you will lose properties that is extended from parent prototype.
console.log({...data});
Upvotes: 0