In my find function. The parameter 'item' is always Null. I wonder if there are some problems about inserting or finding of my code. How should I solve it??
var express = require('express');
var routes = require('./routes');
var socket = require('socket.io');
var fs = require('fs');
var app = module.exports = express.createServer();
var Server = require('mongodb').Server,
Db = require('mongodb').Db,
Connection = require('mongodb').Connection;
var host = 'localhost';
var port = Connection.DEFAULT_PORT;
var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:false});
var id ;
db.open(function(err, db) {
//console.log('opened');
app.listen(3000);
});
db.collection('locations', function(err, collection) {
var object= ({'word':'TEST'},{'word':'HELL'},{'img':'terr'});
collection.insert(object, function(err, result) {
console.log(result);
id = object._id;
collection.find({'word':'TEST'}).toArray(function(err, items){
console.log('item' +items);// <-- The item is always NULL
});
});
});
Then I change My code to....
But it still have the error about "Cannot call method collection of null."
db.open(function(err, db) {
db.collection('locations', function(err, collection) {
var object= ({'word':'TEST'},{'word':'HELL'},{'img':'terr'});
collection.insert(object, function(err, result) {
console.log(result);
id = object._id;
collection.find({'word':'TEST'}).toArray(function(err, items){
if(err)
console.log(err);
else
console.log('item' +items);
});
});
});
app.listen(3000);
});
This line:
var object= ({'word':'TEST'},{'word':'HELL'},{'img':'terr'});
use console.log(object);
and see exactly what you are inserting into MongoDB. This code is equivalent to
var object = {'img':'terr'};
That's why you always get null
- you don't insert the document you are looking for.
If you want to pass multiple documents, then use array:
var object= [{'word':'TEST'},{'word':'HELL'},{'img':'terr'}];