Elliott McNary
Elliott McNary

Reputation: 1209

How to check for document already in database before POST - MongoDB, NodeJS

I am trying to check to see if a document is already in the database before posting. I am posting via a jQuery.post() method to my endpoint which is api/songs.

What I want to check is to see if the song is already in the database. I can check that by querying the songId parameter that I am pushing to the database. If the song is already in the database I want to increment a number by 1.

What I have been trying to do is use mongo's findOne(), but I can't get it to work in the POST. My post route looks like this:

router.post('/api/songs', function(req, res){

    if(Song.findOne({songId: req.body.songId}).length > -1){
        console.log('already in there fam')
    } else{
    var song = new Song();

    song.artistName = req.body.artistName;
    song.titleName = req.body.titleName;
    song.songId = req.body.songId;
    song.songImg = req.body.songImg;


    song.save(function(err) {
        if (err) {
            console.log("Error: " + err)
        } else {
            console.log("created fam")
        }
    })

    };
    console.log(song);
    return res.json({message: "SongCreated"})

})

My problem is that I can't figure out what the findOne is returning. I want it to return a boolean so i've tried count() and length() but can't get it to return true. The req posts to the DB no matter what.

Any ideas?

Upvotes: 0

Views: 75

Answers (1)

Volodymyr Synytskyi
Volodymyr Synytskyi

Reputation: 4055

All i/o operations in node.js are asynchronous. Your Song.findOne operation is asynchronous as well. You should wait for it to complete via callback functionality and then check the result of it.

Mongoose findOne method returns a promise. You can read more info about it here.

Example of promise execution:

var query = Song.findOne({songId: req.body.songId})
query.exec(function(err, song) {

})

Try the following code:

 router.post('/api/songs', function(req, res){
    Song.findOne({songId: req.body.songId}, function(err, song){
        if (err) {
            return console.log("Error: " + err)
        }
        if(song){
            return console.log('already in there fam')
        }
        var song = new Song();

        song.artistName = req.body.artistName;
        song.titleName = req.body.titleName;
        song.songId = req.body.songId;
        song.songImg = req.body.songImg;


        song.save(function(err) {
          if (err) {
            console.log("Error: " + err)
          } else {
            console.log("created fam")
          }
        })

        console.log(song);
        return res.json({message: "SongCreated"})
    })
})

Upvotes: 1

Related Questions