MongoDB 可以这样写
db.getCollection('users').find({})
或者
db.users.find({})
这里的 db
是什么,在代码中应该怎样定义?
在 mongoose 通常这样写:
var User = require('../models/user')
User.find({})
怎样在 mongoose 中应该怎样定义 db
才可以也写作
db.users.find({})
这种写法?
黄舟2017-04-28 09:06:30
(⊙o⊙)… Look at the front of your code to see if there is anything
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/tasks');
Such a code? db
In fact, it is a mongoose connection instance.
And yours User
comes from a Model, right? Your code should look something like this:
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/tasks');
var schema = new mongoose.Schema({
name: String,
path: String
});
module.exports = mongoose.model('User', schema);
So you can use:
User.find({});
漂亮男人2017-04-28 09:06:30
db is the database operation object of the current operation, which refers to the database switched to using use db
给我你的怀抱2017-04-28 09:06:30
module.exports = mongoose.model('User', schema);
It should be like what was said above. Your model file is written like the above. In this case, it can only be written like the following.
var user = require('../model/user');
user.find({})
But if you use mongoose, you have to write it as db.users.find({}), you can change it in the model file:
//model
module.exports = {
'users' : mongoose.model('User', schema)
}
//api
var db = require('../model/user');
db.users.find({})