A
A
Alexander Sharomet2016-07-28 11:45:09
JavaScript
Alexander Sharomet, 2016-07-28 11:45:09

How to check if data exists in mpngoos database?

Hello.
How can I check if the data exists in the database?

//Модель
var mongoose = require('mongoose'),
    express = require('express');
var Schema = mongoose.Schema;
var usersSchema = new Schema({
    _id:Number,
    name: String,
    password: String
});

module.exports = mongoose.model('User', usersSchema);

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var User = require('../models/user-model');

router.get('/', function (req, res) {
    User.findOne({_id:'5'}).limit(1).exec(function(err, user){
        if(err){
            res.send('Error');
        }else {
          if(user._id>0){ //Пытался сделать вот так но ничего не получилось
             res.send('Error');
          }
            res.render('user',{
                title: user.name
            });
        }
    });
});

Thank you.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
napa3um, 2016-07-28
@sharomet

I suspect it meant something like this:

User.findOne({_id: '5'}).exec(function(err, user){
  if(err)
    return res.send('Error');

  if(!user)
    return res.send('User not found');

  res.render('user',{
    title: user.name
  });
});

M
Matvey Safronov, 2016-07-28
@impeee

Through the connection object:

// dbname - имя бд
mongoose.connect('mongodb://127.0.0.1/dbname');
let conn = mongoose.connection;

conn.on('open', () => {
  conn.db.stats( (err, stats) => {
    console.log(stats.objects); // если бд содержит 0 объектов - она пустая
  });
});

I also came up with such a crazy option, it is guaranteed to work in a unix environment, there is no way to check windows:
var exec = require('child_process').exec;

// dbname - имя бд
exec('mongo dbname --eval "db.stats()" | tail -n +3', ( err, stdout ) => {
  try {
    console.log(JSON.parse(stdout).objects);
  } catch(e) {
    //
  }
});

M
MR.TOSTER Gipard Valerievich, 2016-08-19
@zoceb

if(user != null){
console.log(user);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question