MongoDB 和 Mongoose 查询语句写法有什么不同?
世界只因有你
世界只因有你 2017-04-28 09:04:30
0
3
796

MongoDB 可以这样写

db.getCollection('users').find({})

或者

db.users.find({})

这里的 db 是什么,在代码中应该怎样定义?

在 mongoose 通常这样写:

var User = require('../models/user')
User.find({})

怎样在 mongoose 中应该怎样定义 db 才可以也写作

db.users.find({})

这种写法?

世界只因有你
世界只因有你

reply all(3)
黄舟

(⊙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? dbIn 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({});
漂亮男人

db is the database operation object of the current operation, which refers to the database switched to using use db

给我你的怀抱
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({})
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template