Saturday, 8 April 2017

How to check if an Id exist in mongodb array if not push the Id into the array

am using mongoose for my schema design i want to check a user collection if a device id exist in am array if false push the device into the user devices array

here is ma user schema

var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');

var deviceSchema = mongoose.Schema(
{
    macAddress: {type: String, required: true, unique: true},
    createdAt: {type: Date, default: Date.now},
}
)
var Device = mongoose.model('Device', deviceSchema);

module.exports = Device;

here is my user schema

var mongoose = require('mongoose');
var Schema = mongoose.Schema;


var userSchema = Schema(
{
    firstname: {type: String, required: true},
    lastname: {type: String, required: true},
    email: {type: String, required: true, unique: true},
    username: {type: String, required: true, unique: true},
    password: {type: String, required: true},
    createdAt: {type: Date, default: Date.now},
    devices: [{ type: Schema.Types.ObjectId, ref: 'Device1' }]
}
)

var User = mongoose.model('User', userSchema);

module.exports = User;

and here is my nodejs router

router.post('/user/device/:username', function(req, res, next) {
 if(!req.body.macAddress) {
    sendJSONresponse(res, 400, {
        "message": "Device Mac-Address required"
    });
    return;
}
 User.findOne({ username: req.params.username }, function(err, user) {
  if (err) { return next(err); }
  if (!user) { return sendJSONresponse(res, 400, {
        "message": "user not found"
    });
  }
        Device.findOne({macAddress : req.body.macAddress},    function(err, device){
        if(err){return next(err);}
        if(!device){
           sendJSONresponse(res, 400, {
                "message": "No device with that macaddress"
            });
           return;
        }
        User.find({ devices: { $elemMatch: { $eq: req.body.macAddress} } }, function(err, users){
                if(err){return next(err);}
                if(users){
                    sendJSONresponse(res, 400, {
                        "message": "Device already assigned to a user"
                    });
                    return;
                }else{
                    user.devices.push(device._id);
                      user.save(function(err) {
                        if(err){return next(err);}
                        sendJSONresponse(res, 200, user);
                      });
                }
            });

    });
  });
});

after doing all this when i try using the api with postman is tells me The server couldn't send a response: please help me fix my code



via Emibrown

No comments:

Post a Comment