通过ObjectID express js查找用户

时间:2015-07-15 15:10:57

标签: javascript node.js mongodb express

我试图通过mongodb的ObjectId搜索用户但效果不佳。

App.js:

    var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

// Database
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/ePoi');

var routes = require('./routes/index');
var eppoi = require('./routes/eppoi');
var poi = require('./routes/poi');
var user= require('./routes/user');
var trip = require('./routes/trip');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// Make our db accessible to our router
app.use(function(req,res,next){
  req.db = db;
  next();
});

app.use('/', routes);
app.use('/eppoi', eppoi);
app.use('/poi', poi);
app.use('/user', user);
app.use('/trip', trip);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;

user.js的:

/**
 * Created by Matteo on 15/07/2015.
 */
var express = require('express');
var router = express.Router();
ObjectID = require('mongodb').ObjectID;
var db;


//USER
/*
 Visualizzo gli utenti
 */
router.get('/userlist', function(req, res) {
    db = req.db;
    var collection = db.get('user');
    collection.find({},{},function(e,docs){
        res.json(docs);
    });
});

/*
 * POST Inserisce i poi ricevuti da foursquare nella collection poilist
 */
router.post('/adduser', function(req, res) {
    db = req.db;
    var userdb={};
    var user=req.body;

    //dati personali utente
    var nome=user.nome;
    var cognome=user.cognome;
    var email=user.email;
    var sesso=user.sesso;
    var residenza=user.residenza;
    var datanascita=user.datanascita;
    var id_fb=user.id_fb;
    var preferiti=user.preferiti;
    var tipo_di_viaggio=user.tipo_di_viaggio;

    //array con gli indici dei percorsi
    var id_trip= user.id_trip;

    //preferenze utente
    var likeCount=user.likeCount;
    var macro=Object.keys(likeCount);

    var dbLikeCount={};
    var microCont={};

    for(var i=0; i<macro.length; i++){
        var micro=Object.keys(likeCount[macro[i]]);

        for(var j=0; j<micro.length; j++){
            var contenuto=likeCount[macro[i]];
            var like=(contenuto[micro[j]]).like;
            var dislike=(contenuto[micro[j]]).dislike;
            var poilike=Object.keys((contenuto[micro[j]]).poilike);
            var poidislike=Object.keys((contenuto[micro[j]]).poidislike);
            microCont[micro[j]]={"like":like,
                "dislike":dislike,
                "poilike":poilike,
                "poidislike":poidislike};
        }
        dbLikeCount[macro[i]]=microCont;

    }
    //creazione dell'utente che sarà poi inserito nel db
    userdb={"nome":nome,
        "cognome":cognome,
        "email": email,
        "sesso":sesso,
        "residenza":residenza,
        "datanascita":datanascita,
        "id_fb":id_fb,
        "id_trip":id_trip,
        "likeCount":dbLikeCount,
        "preferiti": preferiti};

    console.log(JSON.stringify(userdb));

    //inserimento utente nel db
    var collection = db.get('user');
    collection.insert(userdb, function(err, result){
        res.send(
            (err === null) ? { msg: '' } : { msg: err }
        );
    });
});

/*
 USER BY NAME
 */
router.get('/:name', function(req, res) {
    db = req.db;
    var name=req.params.name;
    console.log(name);
    var collection = db.get('user');
    collection.find({"nome":name},function(e,docs){
        res.json(docs);
    });
});

/*
 USER BY ID
 */
router.get('/:id', function(req, res) {
    db = req.db;

    var newObjectId = new ObjectID(req.params.id)
    console.log(newObjectId);
    var collection = db.get('user');
    collection.find({"_id": newObjectId},{},function(e,docs){
        res.json(docs);
    });
});




module.exports = router;

client.js

$("#btnUserById").on('click', userById);
function userById(){

    var id="55a3e3337b2f33a45bad7c3b";

    // Use AJAX to post the object to our adduser service
    $.ajax({
        contentType: 'application/json',
        type: 'GET',
        async:true,
        url: '/user/' + id,
        dataType: 'JSON'
    }).done(function(response)
    {
        console.log(JSON.stringify(response));
    });

}

我正在尝试传递数据库中的id,我想用objectid那个步骤查找用户,但我的查询结果是:[],即使在数据库中存在用户这个标识。

1 个答案:

答案 0 :(得分:1)

您似乎使用相同的端点进行名称和ID查询。

相反,请尝试按如下方式修改查询端点:

router.get('/:id', function(req, res) { .. }

router.get('/id/:id', function(req, res) { .. }

router.get('/:id', function(req, res) { .. }

router.get('/name/:name', function(req, res) { .. }

陈旧,短视的回答

如果您在没有任何ORM的情况下使用mongodb(例如猫鼬,水线等),则需要先将id字符串转换为ObjectID。

var ObjectID = require('mongodb').ObjectID;
objId = new ObjectID(idString); 

然后搜索objId。如果有帮助,请告诉我们。