我有一个带有产品的var,如果我控制台将其注销,则会显示此信息。
Query {
_mongooseOptions: {},
mongooseCollection:
NativeCollection {
collection: null,
opts: { bufferCommands: true, capped: false },
name: 'products',
collectionName: 'products',
conn:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: null,
port: null,
user: null,
pass: null,
name: null,
options: null,
otherDbs: [],
_readyState: 0,
_closeCalled: false,
_hasOpened: false,
_listening: false },
queue: [],
buffer: true,
emitter:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined } },
model:
{ [Function: model]
hooks: Kareem { _pres: {}, _posts: {} },
base:
Mongoose {
connections: [Object],
plugins: [],
models: [Object],
modelSchemas: [Object],
options: [Object] },
modelName: 'Product',
model: [Function: model],
db:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: null,
port: null,
user: null,
pass: null,
name: null,
options: null,
otherDbs: [],
_readyState: 0,
_closeCalled: false,
_hasOpened: false,
_listening: false },
discriminators: undefined,
schema:
Schema {
obj: [Object],
paths: [Object],
subpaths: {},
virtuals: [Object],
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [Object],
_indexes: [],
methods: {},
statics: {},
tree: [Object],
_requiredpaths: undefined,
discriminatorMapping: undefined,
_indexedpaths: undefined,
query: {},
childSchemas: [],
s: [Object],
options: [Object],
'$globalPluginsApplied': true },
collection:
NativeCollection {
collection: null,
opts: [Object],
name: 'products',
collectionName: 'products',
conn: [Object],
queue: [],
buffer: true,
emitter: [Object] },
Query: { [Function] base: [Object] },
'$__insertMany': [Function],
insertMany: [Function] },
schema:
Schema {
obj:
{ imagePath: [Object],
title: [Object],
description: [Object],
price: [Object] },
paths:
{ imagePath: [Object],
title: [Object],
description: [Object],
price: [Object],
_id: [Object],
__v: [Object] },
subpaths: {},
virtuals: { id: [Object] },
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [ [Object], [Object], [Object], [Object] ],
_indexes: [],
methods: {},
statics: {},
tree:
{ imagePath: [Object],
title: [Object],
description: [Object],
price: [Object],
_id: [Object],
id: [Object],
__v: [Function: Number] },
_requiredpaths: undefined,
discriminatorMapping: undefined,
_indexedpaths: undefined,
query: {},
childSchemas: [],
s: { hooks: [Object], kareemHooks: [Object] },
options:
{ retainKeyOrder: false,
typeKey: 'type',
id: true,
noVirtualId: false,
_id: true,
noId: false,
validateBeforeSave: true,
read: null,
shardKey: null,
autoIndex: null,
minimize: true,
discriminatorKey: '__t',
versionKey: '__v',
capped: false,
bufferCommands: true,
strict: true,
pluralization: true },
'$globalPluginsApplied': true },
op: 'find',
options: { retainKeyOrder: false },
_conditions: {},
_fields: undefined,
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection:
NodeCollection {
collection:
NativeCollection {
collection: null,
opts: [Object],
name: 'products',
collectionName: 'products',
conn: [Object],
queue: [],
buffer: true,
emitter: [Object] },
collectionName: 'products' },
_traceFunction: undefined,
_castError: null,
_count: [Function],
_execUpdate: [Function],
_find: [Function],
_findOne: [Function],
_findOneAndRemove: [Function],
_findOneAndUpdate: [Function] }
我正在尝试使用#each
来获取产品,然后让我们首先说出标题。
这是使用node
的索引js中的方法 var express = require('express');
var router = express.Router();
var Product = require('../models/product');
/* GET home page. */
router.get('/', function(req, res, next) {
Product.find({}, function (err, products) {
// check for and handle query errors
if (err) {
console.error('Product.find() error', err);
return next(err);
}
// continue to render the view with `products` available
console.log(products);
res.render('shop/index', { title: 'Shopping Cart', products: products });
});
});
module.exports = router;
这是index.hbs的foreach句子
{{#each products}}
<p>{{products.price}}</p>
{{/each}}
我尝试了不同的方式,例如#each this
,然后得到它,但似乎不起作用。
如果我在db中搜索
,只需要填写> db.products.find()
{ "_id" : ObjectId("5855c55482d8722419e21a7d"), "imagePath" : "https://upload.wikimedia.org/wikipedia/en/thumb/5/5e/Gothiccover.png/250px-Gothiccover.png", "title" : "weeee", "description" : " AWeeesomeee", "price" : "15", "__v" : 0 }
{ "_id" : ObjectId("5855c55482d8722419e21a7e"), "imagePath" : "https://upload.wikimedia.org/wikipedia/en/thumb/5/5e/Gothiccover.png/250px-Gothiccover.png", "title" : "Gowwww", "description" : " this is great", "price" : "15", "__v" : 0 }
{ "_id" : ObjectId("5855c55482d8722419e21a7f"), "imagePath" : "https://upload.wikimedia.org/wikipedia/en/thumb/5/5e/Gothiccover.png/250px-Gothiccover.png", "title" : "killaa crw", "description" : " i love it", "price" : "15", "__v" : 0 }
{ "_id" : ObjectId("5855c55482d8722419e21a80"), "imagePath" : "https://upload.wikimedia.org/wikipedia/en/thumb/5/5e/Gothiccover.png/250px-Gothiccover.png", "title" : "joker", "description" : " kill em", "price" : "15", "__v" : 0 }
{ "_id" : ObjectId("5855c55482d8722419e21a81"), "imagePath" : "https://upload.wikimedia.org/wikipedia/en/thumb/5/5e/Gothiccover.png/250px-Gothiccover.png", "title" : "harley", "description" : " naughtttyyy", "price" : "15", "__v" : 0 }
{ "_id" : ObjectId("5855c55482d8722419e21a82"), "imagePath" : "https://upload.wikimedia.org/wikipedia/en/thumb/5/5e/Gothiccover.png/250px-Gothiccover.png", "title" : "suicide", "description" : " squad", "price" : "15", "__v" : 0 }
> db.products.count()
6
App.js文件
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressHbs = require('express-handlebars');
var mongoose = require('mongoose');
var routes = require('./routes/index');
var app = express();
app.connect('localhost:27017/shopping');
// view engine setup
app.engine('.hbs', expressHbs({defaultLayout : 'layout', extname: '.hbs' }));
app.set('view engine', '.hbs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
答案 0 :(得分:1)
Mongoose'model.find()
不会像Mongo的命令行那样直接返回结果。
var products = Product.find();
它希望在conditions
之后直接向其提供回调函数,或者提供给它返回的Query
object的方法:
function proceedWithProducts(err, products) {
if (err) {
// handler query error
} else {
// use products
}
}
// a couple options...
Product.find({}, proceedWithProducts);
Product.find().exec(proceedWithProducts);
在路线中:
/* GET home page. */
router.get('/', function(req, res, next) {
Product.find({}, function (err, products) {
// check for and handle query errors
if (err) {
console.error('Product.find() error', err);
return next(err);
}
// continue to render the view with `products` available
console.log(products);
res.render('shop/index', { title: 'Shopping Cart', products: products });
});
});