1

I'm new to mongodb , and i try to insert data in database through my html page using post method. and i use mongoose in server side. here is my code look like.

 var LoginInfoSchema = new mongoose.Schema
 ({
     _id : String,
     user: String,
     password: String
 });


 var user = mongoose.model('user',LoginInfoSchema);

 app.post('/login', function(req, res) {
    new user({
          _id : req.body.email,
          user : req.body.user,
          password : req.body.password
            }).save(function(err,doc){
        if(err) res.json(err);
        else res.redirect('/');
    });
    mongoose.connect('mongodb://localhost:27017/UserInfo',function(err,db){
        if(err) console.log(err);
        db.collection("users").insertOne(user, function(error, result) {
        if(error) console.log(error);
        console.log("1 document inserted");
      db.close();
    });

  });
  });

whenever i insert data from localhost html page it will inserted successfully , i see that from mongo.exe terminal but i got error that is

name: 'MongoError', message: 'Write batch sizes must be between 1 and 100000. Got 0 operations.', ok: 0, errmsg: 'Write batch sizes must be between 1 and 100000. Got 0 operations.', code: 16, codeName: 'InvalidLength', [Symbol(mongoErrorContextSymbol)]: {} }

i search everywhere i cannot solve it . what its exactly mean please answer.

Marsroverr
  • 556
  • 1
  • 6
  • 23
Sats17
  • 95
  • 1
  • 1
  • 10

4 Answers4

4

First I would use mongoose.connect() on top of your file and outside from the route handler.

Then when you use user.save(), you have already saved data into your DB and thanks to the callback function you can handle potential errors or display some success message. So db.collection.("users").insertOne() is kind of redundant.

Try this code maybe ? :

mongoose.connect('mongodb://localhost:27017/UserInfo');

var LoginInfoSchema = new mongoose.Schema({
  _id : String,
  user: String,
  password: String
});

var user = mongoose.model('user',LoginInfoSchema);

app.post('/login', function(req, res) {
  new user({
    _id : req.body.email,
    user : req.body.user,
    password : req.body.password
  }).save(function(err,doc) {
    if(err) res.json(err);
    res.redirect('/');
  });
});

Hope that helps, Cheers

Noé VIRICEL
  • 208
  • 1
  • 3
  • 13
  • thanks for help , can you describe what is difference user.save() and insert.One(). – Sats17 Aug 06 '18 at 15:48
  • check that answer : https://stackoverflow.com/questions/16209681/what-is-the-difference-between-save-and-insert-in-mongo-db – Noé VIRICEL Aug 06 '18 at 15:56
  • your's above code is correct , but i have question that in save function you did not mention collection name "users" so how can it find to save document in "users" collection. – Sats17 Aug 06 '18 at 17:04
  • Ohh ok, when you do "new user({})" you are creating a new "user" instance from the 'user' model. Then you chain .save() function to your instance, so it acts on the user's model / collection. – Noé VIRICEL Aug 07 '18 at 18:10
1

I spent the last two weeks with this error and just got it resolved. I am using kotlin on jetty and the official MongoDB drive. This link in stackoverflow was the closest result I got. In the end, I was missing the to call documentCodec?.encode(writer, document, encoderContext) at the end of the "encode" funcion.

The code bellow got rid of the error:

override fun encode(writer: BsonWriter?, value: User?, encoderContext: EncoderContext?) {
    document["_id"] =  value?._id
    document["name"] = value?.name
    documentCodec?.encode(writer, document, encoderContext)
}`
Gaslan
  • 808
  • 1
  • 20
  • 27
TheSidh
  • 11
  • 2
0

The MongoDB error "Write batch sizes must be between 1 and 100000. Got 0 operations." results from trying to apply a write operation to no arguments, e.g. update an array of zero documents:

db.runCommand(
   {
      update: 'some-collection',
      updates: [],   // Uh-oh, no documents!
      comment: 'this is gonna fail',
   }
)

The OP's code results in this error because the call to insertOne is passed the Mongoose constructor user rather than a document created with new user(...).

polo-language
  • 826
  • 5
  • 13
-1

I too also got stuck in the same error for quite a long. The above answers are perfect to solve the error but I would also suggest you to check the sequence of the parameters(object & callback function) you have sent to the MongoDB connect function. MongoClient.connect(function(parameters))

From controllers to the models when we send

Thanks