Javascript Mongoose/Mongodb:从填充的查询数据中排除字段
我在MEAN环境中使用以下mongoose查询来查找和输出特定作者及其对应的书籍Javascript Mongoose/Mongodb:从填充的查询数据中排除字段,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我在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
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
});
我还想从来自外部文档的填充数据中排除“\u id”和“\u v”字段。如何实现这一点?的第二个参数是字段选择字符串,因此您可以按以下方式执行:
Author
.findOne({personcode: code})
.select('-_id -__v')
.populate('bookids', '-_id -__v')
.exec(function (err, data) {
//foo
});
请注意,您应该将字段选择组合成一个字符串。谢谢JohnnyHK,对于对象参数,此操作有效:
Entity.populate({
path: 'bookids',
// some other properties
match: {
active: true
},
// some other properties
select: '-_id -__v' // <-- this is the way
}).then(...) // etc
Entity.populate({
路径:“bookids”,
//其他一些属性
匹配:{
主动:正确
},
//其他一些属性
选择:'-\u id-\u v'/我是来寻找一些稍微不同的东西的。以防万一有人需要和我一样的东西
您可以指定在创建架构期间自动填充的特定字段,如下所示
const randomSchema = mongoose.Schema({
name: {type: String,trim: true},
username: {type: String,trim: true},
enemies: {
type: ObjectId,
ref: randomMongooseModel,
autopopulate:{
select: '-password -randonSensitiveField' // remove listed fields from selection
}
},
friends: {
type: ObjectId,
ref: randomMongooseModel,
autopopulate:{
select: '_id name email username' // select only listed fields
}
}
});
我在本例中使用mongoose autopopulate插件来单独排除
User.findOne({_id: userId}).select("-password")
使用架构排除的步骤
var userSchema = mongoose.Schema({
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
select: false,
},
});
或者这也会起作用
db.collection.find({},{"field_req" : 1,"field_exclude":0});
我们还可以填充多个引用,然后使用excluder参数将从所有填充的模式中排除字段Author.findOne({personcode:code})。选择('-\u id-\u v')。填充('bookids shelfId rowId','-\u id-\u v')。exec(函数(err,data){//foo})