.save
메서드 에서 생성 된 문서 또는 문서를 반환하는 다른 메서드가 주어지면 해당 문서를 기본 JSON 유형을 사용하는 일반 자바 스크립트 객체로 어떻게 변환 할 수 있습니까? 나는 시도했다 .toJSON
및 .toObject
하지만 문자열을 대신 할 때 그들은 둘 다 여전히 몽구스의 ObjectId가 데이터 유형을 유지 :
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
을 사용할 수 있다는 것을 알고 .lean()
있지만 문서와 일반 객체 버전이 특히 필요합니다.
미리 감사드립니다
먼저 toObject
,,을 JSON.stringify
차례로 사용할 수 있습니다 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);
});
});
의 결과는 console.log(typeof json._id)
입니다 string
.
또한 버전 키를 제거하기 위해 versionKey
스키마 정의에서 false 옵션을 적용 할 수 있습니다 .
const mongoose = require("mongoose");
const catSchema = new mongoose.Schema({ name: String }, { versionKey: false });
const Cat = mongoose.model("Cat", catSchema);
module.exports = Cat;
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다