gpt4 book ai didi

node.js - 如何在mongoose中间件中定义模型和方法?

转载 作者:太空宇宙 更新时间:2023-11-04 00:38:11 25 4
gpt4 key购买 nike

我是 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" }
>

我的问题:

  1. 'ContactModel' 到底是什么意思?在mongoose.model('ContactModel',ContactSchema);代表什么? 是自定义的名称还是db中的集合名称?

  2. 我想为模型创建一个方法(增删改查任务)

ContactSchema.methods.selectAll = function (){
// code here
}

此方法可以选择 mongo 中集合的所有文档,但我的 ContactModel.find函数返回空项。

$ 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 时 Mongoose 的API。如何做到这一点?

最佳答案

很高兴您已经以某种方式解决了您的问题。但这只是为了解决您面临的问题的根本原因。希望其他人觉得它有帮助。

我认为您在 mongoose 之前已经创建了一个名为 contactlist 的数据库和一个名为 contactlist 的集合。而 mongoose 试图变得聪明,将集合名称作为模型复数的名称(lib/npm 源代码 reference ,所有相关规则都在 this file 中定义)。在您的情况下,它可能创建了一个名为 contactlists

的集合

尽管您可以选择在创建模型时通过将其作为第三个参数传递给模型来显式命名您的集合(按照您的方式):

var ContactSchema = new Schema({ name : String /* , .....  */ },{collection : 'contactlist'});

<小时/>这种行为在 Mongoose 模型 API reference 中有清楚的记录。 :

When no collection argument is passed, Mongoose produces a collection name by passing the model name to the utils.toCollectionName method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option.

关于node.js - 如何在mongoose中间件中定义模型和方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38035794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com