在我的猫鼬模式中,我有一个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);
});
它应该这样做。