Octtavius
Octtavius

Reputation: 591

Why can't I save another object in mongoose?

I am trying to save user to database, but if it is not there, then create one. But it is saved only first object(user). If i try to add another user it doesn;t want. Do anybody know what would be the problems?

Model

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

var childSchema = (
    {
        _id: false,
        movieId: {
            type: Number,
            index: true
        },
        value: {
            type: Number
        }
    }
);

var user = new Schema({
    name: {
        type: String
    },
    movieCollections: [childSchema]
});

clickPoint.plugin(integerValidator);
clickPoint.plugin(uniqueValidator);

//export model...
module.exports = mongoose.model("User", user);

Controller:

var User = require('../Models/user');

User.findOne({name: aName}, function (err, data) {
    if(!err) {
        //if data was found
        if(data) {
            console.log('we found somebody');
        }
        else {
            var entry = new User({
                name: aName,
                movieCollections: [{
                    movieId: 12355,
                    value: 23
                }]
            });

            entry.save();
        }
    }
});

Upvotes: 0

Views: 43

Answers (1)

Sparw
Sparw

Reputation: 2743

Can you try to display any error of entry.save() ?

    entry.save(function(err) {
       if (err) console.log(err);
    });

EDIT

I think you have to set your Schema like this :

    var childSchema = (
    {
        _id: false,
        movieId: {
            type: Number,
            index: false // Now you can have duplicate movieId
        },
        value: {
            type: Number
        }
    }
);

Hope it helps

Upvotes: 1

Related Questions