IT박스

Mongoose 문서를 json으로 변환

itboxs 2020. 11. 29. 10:07
반응형

Mongoose 문서를 json으로 변환


이런 식으로 몽구스 문서를 json으로 반환했습니다.

UserModel.find({}, function (err, users) {
    return res.end(JSON.stringify(users));
}

그러나 user .__ proto__도 반환되었습니다. 그것없이 어떻게 돌아갈 수 있습니까? 나는 이것을 시도했지만 작동하지 않았습니다.

UserModel.find({}, function (err, users) {
    return res.end(users.toJSON());    // has no method 'toJSON'
}

mongoosejs의 lean () 시도해 볼 수도 있습니다 .

UserModel.find().lean().exec(function (err, users) {
    return res.end(JSON.stringify(users));
}

늦은 답변이지만 스키마를 정의 할 때 이것을 시도 할 수도 있습니다.

/**
 * toJSON implementation
 */
schema.options.toJSON = {
    transform: function(doc, ret, options) {
        ret.id = ret._id;
        delete ret._id;
        delete ret.__v;
        return ret;
    }
};

그 주 retJSON'ed 객체이며, 몽구스 모델의 인스턴스 아니다. getter / setter없이 객체 해시에서 바로 작업 할 수 있습니다.

그리고:

Model
    .findById(modelId)
    .exec(function (dbErr, modelDoc){
         if(dbErr) return handleErr(dbErr);

         return res.send(modelDoc.toJSON(), 200);
     });

편집 : 2015 년 2 월

누락 된 toJSON (또는 toObject) 메서드에 대한 솔루션을 제공하지 않았기 때문에 사용 예제와 OP의 사용 예제 간의 차이점을 설명하겠습니다.

OP :

UserModel
    .find({}) // will get all users
    .exec(function(err, users) {
        // supposing that we don't have an error
        // and we had users in our collection,
        // the users variable here is an array
        // of mongoose instances;

        // wrong usage (from OP's example)
        // return res.end(users.toJSON()); // has no method toJSON

        // correct usage
        // to apply the toJSON transformation on instances, you have to
        // iterate through the users array

        var transformedUsers = users.map(function(user) {
            return user.toJSON();
        });

        // finish the request
        res.end(transformedUsers);
    });

내 예 :

UserModel
    .findById(someId) // will get a single user
    .exec(function(err, user) {
        // handle the error, if any
        if(err) return handleError(err);

        if(null !== user) {
            // user might be null if no user matched
            // the given id (someId)

            // the toJSON method is available here,
            // since the user variable here is a 
            // mongoose model instance
            return res.end(user.toJSON());
        }
    });

우선, 아마 toObject()대신 해보 toJSON()시겠습니까?

Secondly, you'll need to call it on the actual documents and not the array, so maybe try something more annoying like this:

var flatUsers = users.map(function() {
  return user.toObject();
})
return res.end(JSON.stringify(flatUsers));

It's a guess, but I hope it helps


model.find({Branch:branch},function (err, docs){
  if (err) res.send(err)

  res.send(JSON.parse(JSON.stringify(docs)))
});

I found out I made a mistake. There's no need to call toObject() or toJSON() at all. The __proto__ in the question came from jquery, not mongoose. Here's my test:

UserModel.find({}, function (err, users) {
    console.log(users.save);    // { [Function] numAsyncPres: 0 }
    var json = JSON.stringify(users);
    users = users.map(function (user) {
        return user.toObject();
    }
    console.log(user.save);    // undefined
    console.log(json == JSON.stringify(users));    // true
}

doc.toObject() removes doc.prototype from a doc. But it makes no difference in JSON.stringify(doc). And it's not needed in this case.


Maybe a bit astray to the answer, but if anyone who is looking to do the other way around, you can use Model.hydrate() (since mongoose v4) to convert a javascript object (JSON) to a mongoose document.

An useful case would be when you using Model.aggregate(...). Because it is actually returning plain JS object, so you may want to convert it into a mongoose document in order to get access to Model.method (e.g. your virtual property defined in the schema).

PS. I thought it should have a thread running like "Convert json to Mongoose docs", but actually not, and since I've found out the answer, so I think it is not good to do self-post-and-self-answer.


You can use res.json() to jsonify any object. lean() will remove all the empty fields in the mongoose query.

UserModel.find().lean().exec(function (err, users) { return res.json(users); }


Try this options:

  UserModel.find({}, function (err, users) {
    return res.end( JSON.parse(JSON.stringify(users)) );
    //Or: 
    //return JSON.parse(JSON.stringify(users));
  }

It worked for me:

Products.find({}).then(a => console.log(a.map(p => p.toJSON())))


also if you want use getters, you should add its option also (on defining schema):

new mongoose.Schema({...}, {toJSON: {getters: true}})

참고URL : https://stackoverflow.com/questions/9952649/convert-mongoose-docs-to-json

반응형