node.js - When I use mongoose & connect MongoDB, I can insert and get data. But unable to find data using MongoClient -
my code follows. open localhost/users/,brower return
{"_id":"55519446e063d4c409f93f00","username":"justnode","__v":0}
but when open mongo shell , input: use student
, db.student.find()
,i can't find anything. mongodb version 3.0.1
, nodejs version 0.12.2
, os centos 6.4
var express = require('express'); var bodyparser = require('body-parser'); var mongoose = require('mongoose'); var app = express(); mongoose.connect('mongodb://localhost/student', function (error) { if (error) { console.log(error); } }); var schema = mongoose.schema; var userschema = new schema({ username: {type: string, unique: true} }); var usermodel = mongoose.model('usermodel', userschema); app.use(bodyparser.json()); app.use(bodyparser.urlencoded({ extended: false })); /* post content follows { "username": "justnode" } */ app.post('/users/create', function (req, res) { console.log("in /users/create"); var usermodeljson = req.body; var usermodel = new usermodel(usermodeljson); usermodel.save(function(error) { if(error) { console.log(error); return res.json({msg: "error"}); } console.log("user created: " + usermodel.username); res.json(usermodel); }); }); /* open localhost/users/ brower return {"_id":"55519446e063d4c409f93f00","username":"justnode","__v":0}] when open mongo client: db.student.find() can't find */ app.get('/users', function (req, res) { usermodel.find({}, function (err, docs) { res.json(docs); }); }); var serverapp = app.listen(80, function () { console.log('express server listening on port ' + serverapp.address().port); });
change database(student), schema(userschema) , model(usermodel)'s name , try again. case, after changing variable's name , restart, works. (i've no idea why, maybe mongoose or mongo shell has bug?)
Comments
Post a Comment