如何通过javascript使用mongoose从mongoDB获取一个字段的值

这是我在数据库newDb下收集用户的一个文件,

> db.users.find().pretty() { "_id" : ObjectId("57025801593e301831ef3c72"), "country" : "US", "gender" : "Male", "lastName" : "Ks", "firstName" : "Balajee", "password" : "$2a$08$.Qts1uaOJiyH.A0LM9QeGOB1EBfItB2nV29RxLVbloDnzAggIuGf6", "email" : "balajee41@gmail.com", "position" : [ "1", "2" ], "__v" : 1, "operation" : "add", "userip" : "11"} 

我怎样才能从这个文件中获取位置,操作和userip并用它来执行一个函数? 这是一个单独的Javascript文件中除主节点文件之外的function。

 function verifyOTP() { var position = user.position; var operation = user.operation; var useripp = user.userip; check(arr, position, operation, useripp); } 

       

网上收集的解决方案 "如何通过javascript使用mongoose从mongoDB获取一个字段的值"

如果你使用mongoose ,定义模型和使用它,比原始收集好得多。

首先在文件user.js定义一个模型:

 var mongoose = require('mongoose'); var Schema = mongoose.Schema; var userSchema = new Schema({ firstName: String, lastName: String, // TODO: add other required fields }); mongoose.model('user', userSchema); exports.userSchema = userSchema; 

validation.js添加validation逻辑,例如:

 exports.verifyOTP = function(user) { var position = user.position; var operation = user.operation; var useripp = user.userip; check(arr, position, operation, useripp); // TODO: what is arr? }; 

user-service.js中添加下面的代码:

 var User = require('mongoose').model('user'); var validation = require('./validation'); var filter = { name: 'firstName' }; // TODO: use real filter here var fields = 'position operation userip'; User .findOne(filter, fields) .then(validation.verifyOTP) .catch(err => console.log(err)); 

尝试这个:

 var Helper = require('path_to_the_module_where_the_method_check_is_defined_and_exported'); function verifyOTP(user) { var position = user.position; var operation = user.operation; var useripp = user.userip; Helper.check(position, operation, useripp); }; var query = { // Your query here }; var projection = { position: 1, operation: 1, userip: 1, _id: 0 }; User.findOne( query, projection, function(err, user) { if(err) console.log("Error: " + JSON.stringify(err)); if(user) verifyOTP(user); });