Convert Mongoose docs to json

匿名 (未验证) 提交于 2019-12-03 09:06:55

问题:

I returned mongoose docs as json in this way:

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

However, user.__proto__ was also returned. How can I return without it? I tried this but not worked:

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

回答1:

You may also try mongoosejs's lean() :

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


回答2:

Late answer but you can also try this when defining your schema.

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

Note that ret is the JSON'ed object, and it's not an instance of the mongoose model. You'll operate on it right on object hashes, without getters/setters.

And then:

Model     .findById(modelId)     .exec(function (dbErr, modelDoc){          if(dbErr) return handleErr(dbErr);           return res.send(modelDoc.toJSON(), 200);      }); 

Edit: Feb 2015

Because I didn't provide a solution to the missing toJSON (or toObject) method(s) I will explain the difference between my usage example and OP's usage example.

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);     }); 

My Example:

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());         }     }); 


回答3:

First of all, try toObject() instead of toJSON() maybe?

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



回答4:

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


回答5:

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.



回答6:

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); }



回答7:

Try this options:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!