Igo*_* P. 12 javascript mongoose mongodb node.js
我在MEAN环境中使用以下mongoose查询来查找和输出特定作者及其相应的书籍.
Author
.findOne({personcode: code})
.select('-_id')
.select('-__v')
.populate('bookids') //referencing to book documents in another collection (->array of bookids)
.select('-_id') //this doens't affect the data coming from the bookids-documents
.select('-__v') //this doens't affect the data coming from the bookids-documents
.exec(function (err, data) {
//foo
});
Run Code Online (Sandbox Code Playgroud)
我还想从来自外部文档的填充数据中排除"_id"和"__v"字段.怎么能实现呢?
Joh*_*yHK 35
第二个参数populate是字段选择字符串,因此您可以这样做:
Author
.findOne({personcode: code})
.select('-_id -__v')
.populate('bookids', '-_id -__v')
.exec(function (err, data) {
//foo
});
Run Code Online (Sandbox Code Playgroud)
请注意,您应该将字段选择组合为单个字符串.
单独排除
User.findOne({_id: userId}).select("-password")
Run Code Online (Sandbox Code Playgroud)
排除使用架构
var userSchema = mongoose.Schema({
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
select: false,
},
});
Run Code Online (Sandbox Code Playgroud)
或者这也行
db.collection.find({},{"field_req" : 1,"field_exclude":0});
Run Code Online (Sandbox Code Playgroud)
感谢 JohnnyHK,对于对象参数,这有效:
Entity.populate({
path: 'bookids',
// some other properties
match: {
active: true
},
// some other properties
select: '-_id -__v' // <-- this is the way
}).then(...) // etc
Run Code Online (Sandbox Code Playgroud)