简体   繁体   中英

MeanJS MongoDb insert issue

I'm creating an application using MEANJS. I've a mongoose schema defined like this:

 var UserdetailSchema = new Schema({
    fullName: {
        type: String,
        trim: true
    },
    userName: {
        type: String,
        trim: true
        },
    mobile: {
        type: String,
        default: '',
        trim: true
    },
    address: {
        type: String,
        trim: true
    },
    suburb: {
        type: String
        },
    user: {
        type: Schema.ObjectId,
        ref: 'User'
    }
    });

mongoose.model('Userdetail', UserdetailSchema);

What I'm trying to achieve is after login user is redirected to edit view to update rest of the info like "mobile, suburb, address" etc which is in userdetails schema.

This is my controller. I've changed default create() method to the following: I'm redirecting to the edit it as soon as the first step of inserting is complete.

// Create new Userdetail for current user
    function create(FullName,UserName) {
        // Create new Userdetail object
        var userdetail = new Userdetails ({
            fullName: FullName,
            userName: UserName
        });

        // Redirect after save
        userdetail.$save(function(response) {
            $location.path('userdetails/' + response._id+'/edit');
            console.log(response._id);
            // Clear form fields
            //$scope.name = '';
        }, function(errorResponse) {
            console.log(errorResponse.data.message);
            $scope.error = errorResponse.data.message;
        });
    };

To create a user details I'm only inserting fullName, and userName as a first step and updating it later.

issue is, it is only allowing me 1 userdetails to insert and if I try to insert another userdetails of another user. it gives an error "Name already exists", though there is no name in the schema.

Server side code to create userdetails

/**
 * Create a Userdetail
 */
    exports.create = function(req, res) {
    var userdetail = new Userdetail(req.body);
    userdetail.user = req.user;

    userdetail.save(function(err) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            res.jsonp(userdetail);
        }
    });
};

在此处输入图片说明

I got it working after droping my collection "userdetails" from shell and trying inserting again. I followed this link Mongodb- Add unique index on an existing collection . It was more of MongoDB issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM