Tok*_*she 5 javascript mongodb node.js express
我正在使用node.js/express,我有一个Mongodb来存储一些数据集.在网页上,用户可以输入,编辑和删除数据(一切正常).例如,要添加数据,我有以下代码:
router.post('/addset', function(req,res) {
var db = req.db;
var collection = db.get('paramlist');
collection.insert(req.body, function(err, result){
res.send(
(err === null) ? { msg: '' } : { msg: err }
);
});
});
Run Code Online (Sandbox Code Playgroud)
在我的app.js文件中,我包含了这些行
// Database
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/paramSet1');
Run Code Online (Sandbox Code Playgroud)
以及
app.use(function(req,res,next){
req.db = db;
next();
});
Run Code Online (Sandbox Code Playgroud)
使数据库的代码的其余部分访问(以下这个教程:http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/,我与这些事情是初学者).
所以这一切都很好.我的问题如下:如果数据库中已存在具有相同名称的数据集并向用户发送消息,我想添加测试.以下回答如何查询MongoDB以测试项是否存在?我尝试使用collection.find.limit(1).size()但我收到了错误
undefined is not a function
Run Code Online (Sandbox Code Playgroud)
我尝试了以下的事情.在上面的成本(router.post)我尝试添加行var收集后...
var findValue = collection.find({name:req.body.name});
Run Code Online (Sandbox Code Playgroud)
如果我然后执行console.log(findValue),我会得到一个巨大的输出JSON.然后我尝试了console.log(findValue.next())但是我得到了同样的错误(undefined不是函数).我也试过了
collection.find({name:req.body.name}).limit(1)
Run Code Online (Sandbox Code Playgroud)
以及
collection.find({name:req.body.name}).limit(1).size()
Run Code Online (Sandbox Code Playgroud)
但也得到这个错误.总而言之,collection.insert,collection.update和collection.remove都可以工作,但find()却没有.另一方面,当我进入mongo shell时,命令工作正常.
任何提示和想法我都会感激不尽.
编辑:console.log(findValue)的输出是:
{ col:
{ manager:
{ driver: [Object],
helper: [Object],
collections: [Object],
options: [Object],
_events: {} },
driver:
{ _construct_args: [],
_native: [Object],
_emitter: [Object],
_state: 2,
_connect_args: [Object] },
helper: { toObjectID: [Function], isObjectID: [Function], id: [Object] },
name: 'paramlist',
col:
{ _construct_args: [],
_native: [Object],
_emitter: [Object],
_state: 2,
_skin_db: [Object],
_collection_args: [Object],
id: [Object],
emitter: [Object] },
options: {} },
type: 'find',
opts: { fields: {}, safe: true },
domain: null,
_events: { error: [Function], success: [Function] },
_maxListeners: undefined,
emitted: {},
ended: false,
success: [Function],
error: [Function],
complete: [Function],
resolve: [Function],
fulfill: [Function],
reject: [Function],
query: { name: 'TestSet1' } }
Run Code Online (Sandbox Code Playgroud)
find返回一个游标,而不是匹配的文档本身。但更适合您的情况是使用findOne:
collection.findOne({name:req.body.name}, function(err, doc) {
if (doc) {
// A doc with the same name already exists
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14384 次 |
| 最近记录: |