如何以编程方式强制 mongoose 查询和 return mongodb 集合中的某个字段?

How to programmatically force mongoose to query and return a certain field in a mongodb collection?

我在mongodb中存储了密码和盐,我可以查询除盐以外的所有其他字段。

架构如下:

var userSchema = new Schema({
firstname     : { type: String, trim: true},
lastname      : { type: String, trim: true},
email         : { type: String, required: true, unique: true, trim:true},
password      : { type: String, required: true},
salt          : { type: String, required: true, trim: true, unique: true},
addedOn       : { type: String, required: false}
});
...

并在此处请求文档:

User.findOne({
    email: req.body.email   
}).exec(function(err, obj) {
    if (err) {
        console.log("MongoDB Error: " + err);
        return res.status(500); // or callback
    } 
    else if (obj) {
        console.log(obj.firstname); //This works
        console.log(obj.salt); // And this doesn't
    }
});

但是当我从终端 运行 db.users.find() 时,这个文档存在并且有盐。

编辑:

我在这里找到了问题的解决方案 How to protect the password field in Mongoose/MongoDB so it won't return in a query when I populate collections?

使用这个你可以强制 mongoose 查询和 return 来自 mongodb 集合的特定字段:

User.findOne({
 email: req.body.email  
},
{ firstname: 1, lastname: 1 , email: 1, password: 1, addedOn: 1}).exec(function(err, obj) {
if (err) {
console.log("MongoDB Error: " + err);
 return res.status(500); // or callback
} 
else if (obj) {
console.log(obj);
});

我喜欢 Mital 的回答,它检索了字段,但由于某种原因返回的值不可用。

这很管用。

User.findOne({
     email: req.body.email 
}).select('+salt').exec(function(err, obj)
{ ... }