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

时间:2016-04-04 13:17:08

标签: javascript node.js mongodb mongoose

这是我的数据库 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"}

如何从此文档中获取位置,操作和userip 并将其用于执行函数? 除了主节点文件之外,这是一个单独的Javascript文件中的函数。

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

2 个答案:

答案 0 :(得分:0)

试试这个:

{{1}}

答案 1 :(得分:0)

如果使用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中添加验证逻辑,例如:

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