【发布时间】:2016-10-28 09:29:17
【问题描述】:
我是 mongodb 和 nodejs 的新手。我创建了一个架构,例如:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ContactSchema = new Schema({
name : String,
email: String,
number : String
});
ContactSchema.methods.selectAll = function (callback){
console.log("I got list contact");
ContactModel.find({}).exec(function(err,items){
if(err)
console.error(err.stack);
else{
var notify = {
'message' : 'select all document successfully',
'data' : items,
'status' : 1
};
console.log(notify);
callback();
};
});
};
var ContactModel = mongoose.model('contactlist',ContactSchema);
module.exports = ContactModel;
假设我已使用'mongodb://localhost:27017/contactlist' 连接到数据库。它有一个数据库名称contactlist,一个集合contactlist 和一些文档
> db.contactlist.find({})
{ "_id" : ObjectId("576e8ac6d68807e6244f3cdb"), "name" : "Tome", "email" : "Tome@gmail.com", "number" : "333-333-333" }
{ "_id" : ObjectId("576e8b4fd68807e6244f3cdc"), "name" : "Trace", "email" : "Trace@gmail.com", "number" : "444-444-444" }
{ "_id" : ObjectId("576e8b4fd68807e6244f3cdd"), "name" : "Tuker", "email" : "Tuker@gmail.com", "number" : "555-444-777" }
>
我的问题:
-
mongoose.model('ContactModel',ContactSchema);中的'ContactModel'到底代表什么? 是自定义的名字还是db中的集合名?- 我想为模型创建一个方法(crud task)
ContactSchema.methods.selectAll = function (){ // code here }
此方法可以选择 mongo 中集合的所有文档,但我的 ContactModel.find 函数返回 null 项。
$ node server
development server is running at 127.0.0.1 port 3000
I got list contact
{ message: 'select all document successfully',
data: [],
status: 1 }
undefined
我的意思是当我使用 find 猫鼬的 api 时。该怎么做?
【问题讨论】: