在我的 Mongoose 架构中,我有一个 id
字段,每个文档都有一个唯一的 ID。这与默认 _id
字段使用的系统相同,如下所示:
var JobSchema = new mongoose.Schema({
id: { type:String, required:true, unique:true, index:true, default:mongoose.Types.ObjectId },
title: { type: String },
brief: { type: String }
});
module.exports = mongoose.model("Job", JobSchema);
现在,如果我查询架构以获取 ID 和标题,我会这样做:
Job.find().select("id title").exec(function(err, jobs) {
if (err) throw err;
res.send(jobs);
});
但是,我发现这会按预期返回 id
和 title
,但它还会返回默认的 _id
字段。为什么会这样,我该如何阻止它?
最佳答案
在 find()
函数中,您可以传递两个参数(条件和投影)。投影是您想要(或不需要)的字段。在您的情况下,您可以将代码更改为
Job.find({}, {_id:0, id: 1, title: 1}, function(err, jobs) {
if (err) throw err;
res.send(jobs);
});
它应该这样做。
关于javascript - id 字段的 Mongoose 请求返回 id 和 _id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27840172/