Sunday 21 May 2017

Unable insert more than 1 entry in MongoDB

Here is my schema. user_id and other_id are supposed to be unique (composite).

var mongoose = require("mongoose");
var uniqueValidator = require('mongoose-unique-validator');

var Schema = mongoose.Schema;

var FriendshipSchema = new Schema({

  user_id: {
    type: String,
    default: "",  
    trim: true,
unique:true,
  },
  other_id: {
    type: String,
    default: "",
unique:true,
  },

  status: {
    type: String,
    index: true,
    default: "none",
  },

});
FriendshipSchema.plugin(uniqueValidator);

module.exports =  mongoose.model('Friendship', FriendshipSchema)

and here is my server-side code. pretty straightforward insert using Mongoose.

app.post('/api/user/friendrequest', function(req, res){
var friendship = new Friendship(req.body);
console.log(req.body);

 Friendship.find({}, function (err, docs) {
        if (docs.length){
console.log('abac');
        }else{
            friendship.save(function(err){

            if (err)
            {
             console.log(err)
            }
            });
        }
    });
    });

I get this response in console but no more than 1 entry is saved in MongoDB. I've deleted indexes as well and its still not working. btw 'user_id' is unique in another Collection. I also don't get any error when i log console.log(err).

{ user_id: 'google-oauth2|117175967810648931400',
  status: 'pending',
  other_id: 'facebook|10209430751350509' }
abac

Here are the indexes for the friendships collection.

 db.friendships.getIndexes()
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "kola.friendships"
        }
]



via Alamgir Qazi

No comments:

Post a Comment