Answer a question

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.

Answers

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

Logo

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐