Answer the question
In order to leave comments, you need to log in
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
});
}
});
});
Answer the question
In order to leave comments, you need to log in
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
});
});
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 объектов - она пустая
});
});
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) {
//
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question