开发者

MongoDB / NodeJS - Data Insert Doesn't Auto Increment Object_ID

Hi There: I'm new to Node.JS, MongoDB, and Mongoose so please forgive me if my questions are naive.

I've wrote a small bit of code to asyncronously send data from a form to the database and then display back on the client.

The inserts are kind of working. Each time I perform a form submission my data is inserted into the 开发者_如何转开发DB, but used the same ObjectID each time, meaning that no increment is happening on the document ID.

Is there something I'm doing wrong? Should I be manually incrementing the ID or is there a different way to handle objects/inserts/etc. with these technologies.

Any help is much appreciated. Thanks.

Code:

// Launch express and server
var express = require('express');
var app = express.createServer();

//connect to DB
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://127.0.0.1/napkin_v1');

//Configure Node w/ Dependencies
app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(require("stylus").middleware({
      src: __dirname + "/public",
      dest: __dirname + "/public",
      compress: false
    }));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  //app.use(require('stylus').middleware({ src: __dirname + '/public' }));
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});


// Define Schema for Message
var Schema = mongoose.Schema;

var messageSchema = new Schema({
    body: { type: String, index: { unique:true}},
    user: { type: String, index: { unique:true}},
    dateCreated: Date,
    tags: String
});

mongoose.model('Message', messageSchema);
var Message = mongoose.model('Message');

//Insert First Message into DB

var message = new Message();


app.get('/', function(req,res){
  Message.find(function(error, docs){
    res.render('layout.jade', {
      locals: {
        title: 'Napkin v0.111',
        messages: docs
      }
    });
  })
})

app.post('/', function(req,res){
  message.user = req.param('user');
  message.body = req.param('body');
  message.save(function() {
    res.redirect('/');
  });
});

//Launch Server
app.listen(3002);
console.log("Express server listening on port %d", app.address().port);


Your message instance is global, so you're not creating new messages. You need to do var message = new Message(); inside the root post function.


Just after var Schema = mongoose.Schema, I guess you will need this var ObjectId = Schema.ObjectId;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜