Convert Mongoose docs to json

2019-01-06 09:42发布

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'
}

8条回答
【Aperson】
2楼-- · 2019-01-06 09:54

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.

查看更多
Fickle 薄情
3楼-- · 2019-01-06 09:56

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.

查看更多
ゆ 、 Hurt°
4楼-- · 2019-01-06 09:57

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

查看更多
可以哭但决不认输i
5楼-- · 2019-01-06 10:05

You may also try mongoosejs's lean() :

UserModel.find().lean().exec(function (err, users) {
    return res.end(JSON.stringify(users));
}
查看更多
爷、活的狠高调
6楼-- · 2019-01-06 10:06

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楼-- · 2019-01-06 10:08

Try this options:

  UserModel.find({}, function (err, users) {
    return res.end( JSON.parse(JSON.stringify(users)) );
    //Or: 
    //return JSON.parse(JSON.stringify(users));
  }
查看更多
登录 后发表回答