node.js 将猫鼬文档转换为 json
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9952649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Mongoose docs to json
提问by Trantor Liu
I returned mongoose docs as json in this way:
我以这种方式将猫鼬文档作为 json 返回:
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:
但是, user.__proto__ 也被返回了。没有它我怎么能回来?我试过这个但没有奏效:
UserModel.find({}, function (err, users) {
return res.end(users.toJSON()); // has no method 'toJSON'
}
回答by ecdeveloper
回答by eAbi
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 retis 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.
请注意,这ret是 JSON 格式的对象,它不是猫鼬模型的实例。您将直接在对象哈希上对其进行操作,而无需 getter/setter。
And then:
进而:
Model
.findById(modelId)
.exec(function (dbErr, modelDoc){
if(dbErr) return handleErr(dbErr);
return res.send(modelDoc.toJSON(), 200);
});
Edit: Feb 2015
编辑:2015 年 2 月
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.
因为我没有为缺少的 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);
});
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());
}
});
回答by Jamund Ferguson
First of all, try toObject()instead of toJSON()maybe?
首先,尝试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
这是一个猜测,但我希望它有所帮助
回答by Fabio Guerra
model.find({Branch:branch},function (err, docs){
if (err) res.send(err)
res.send(JSON.parse(JSON.stringify(docs)))
});
回答by Trantor Liu
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:
我发现我犯了一个错误。根本不需要调用 toObject() 或 toJSON() 。问题中的 __proto__ 来自 jquery,而不是猫鼬。这是我的测试:
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.
doc.toObject() 从文档中删除 doc.prototype。但它在 JSON.stringify(doc) 中没有区别。在这种情况下不需要它。
回答by Leo Li
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.
答案可能有点误入歧途,但如果有人想Model.hydrate()反其道而行之,您可以使用(自 mongoose v4 起)将 javascript 对象 (JSON) 转换为 mongoose 文档。
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).
一个有用的情况是当您使用Model.aggregate(...). 因为它实际上返回的是普通的 JS 对象,所以您可能希望将其转换为 mongoose 文档以便访问Model.method(例如,您在架构中定义的虚拟属性)。
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.
附注。我认为它应该有一个像“ Convert json to Mongoose docs”这样的线程运行,但实际上没有,而且由于我已经找到了答案,所以我认为进行自我发布和自我回答并不好。
回答by Dudi
Try this options:
试试这个选项:
UserModel.find({}, function (err, users) {
//i got into errors using so i changed to res.send()
return res.send( JSON.parse(JSON.stringify(users)) );
//Or
//return JSON.parse(JSON.stringify(users));
}
回答by yaya
It worked for me:
它对我有用:
Products.find({}).then(a => console.log(a.map(p => p.toJSON())))
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):
此外,如果您想使用 getter,您还应该添加它的选项(在定义架构时):
new mongoose.Schema({...}, {toJSON: {getters: true}})
new mongoose.Schema({...}, {toJSON: {getters: true}})
回答by bindaas
You can use res.json() to jsonify any object. lean() will remove all the empty fields in the mongoose query.
您可以使用 res.json() 对任何对象进行 jsonify。Lean() 将删除猫鼬查询中的所有空字段。
UserModel.find().lean().exec(function (err, users) {
return res.json(users);
}
UserModel.find().lean().exec(function (err, users) {
return res.json(users);
}

