简体   繁体   English

如何通过猫鼬使用mongoose从mongoDB获取字段的值

[英]How to get the value of a field from mongoDB using mongoose through javascript

This is a document under the collection users in my database newDb , 这是我数据库newDb中集合用户下的文档,

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

How can I fetch position,operation and userip from this document and use it for executing a function? 如何从本文档中获取位置,操作和用户信息 ,并将其用于执行功能? This is a function in a separate Javascript file apart form the main node file. 这是除主节点文件之外的单独Javascript文件中的函数。

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

Try this: 尝试这个:

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);
});

If you use mongoose it's much better to define model and work with it, than with raw collection. 如果使用mongoose ,定义模型并使用它,比使用原始集合要好得多。

First of all define a model in file user.js : 首先在文件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;

Add validation logic in validation.js for example: 例如,在validation.js添加验证逻辑:

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?
};

And in user-service.js , add the following code: 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM