node-mongoose

1.2.3 • Public • Published

安装方法(how to install?)

npm i node-mongoose --save 
或者(or)
yarn add node-mongoose

使用方法(how to use?)

const Mongo = require('node-mongoose');
Mongo.config({
    //连接mongodb的用户用户名(for connecting mongodb's user)
    user: 'username',
    //连接mongodb的用户密码(for connecting mongodb's password)
    password: 'password',
    //...主机名(hostname)
    hostname: '127.0.0.1',
    //端口号(port)
    port: '27017',
    //数据库名称(database's name)
    db: 'test'
});

实例化(invoke the constructor)

const mongo = new Mongo({
    table1: {
        tableField1: {
            type: String,
            value: 'defaultValue'
        }
    },
    table2: {
        tableField1: {
            type: Number,
            required: true
        },
        tableField2: {
            type: Date
        }
    },
    /*
        ...
    */
});

以上定义schema的可选参数可以查看mongoose的schema可选参数
(the arguments in this constructor is based on the mongoose Schema gotcha)
添加数据(insert data)

async function a(){
    await mongo.insert('table', { key1: 'value1' }, false);
}
//or
function a(){
    mongo.insert('table', { key1: 'value1' }, false, (err, doc) => {
        //TODO sth with err and doc
        //err means the error message 
    })
}
//您可以不填写第三个参数,当您不填写时默认值就是true
//you can not fill in the third parameter, the default value is true when you dont fill in
mongo.insert('table', { field1: 'value1' }, true, (err, doc) => {
    //TODO sth with err and doc
    //err means the error message 
}); 
//=== (equals to)
mongo.insert('table', { field1: 'value1' }, (err, doc) => {
    //TODO sth with err and doc
    //err means the error message 
});
//传入回调函数的doc参数与使用await的返回值是相同的
//callback's parameter doc is equals to the await function's return's value

返回值( will return an object)

//(this means its a repeat data)
return { status: 2, message: '数据重复'};
//(this means insert successfully)
return { status: 1, message: '添加成功'};
//(message means insert failed, this reason is the error message)
return { status: 0, message: '添加失败', reason: error}

查找数据(find data)

async function a(){
    await mongo.findInTable( 'table', { field1: 'value1' } );
}
//or
function a(){
    mongo.findInTable('table', { field1: 'value1'}, (err, doc) => {
        //TODO sth with err and doc
        //err means the error message
    })
}
//传入回调函数的doc参数与使用await的返回值是相同的
//callback's parameter doc is equals to the await function's return's value

返回值( will return an object):

//(length是结果的长度,data是个以数组类型的结果集,查询的每个结果都是一个对象)
//(message means find data successful, result is this data.The result is an Array, every data in result is an object in this Array)
return {status: 1, body: doc, reason: undefined};
//(查询错误,reason是错误信息)
//(find failed, the reason is the error message)
return {status: 0, body: undefined, reason: err};

删除数据(delete data)
_1._删除符合条件的所有数据(Delete all data that meets the criteria)

async function a(){
    await mongo.deleteMany('table', {field1: 'value1'});
}
//or
function a(){
    mongo.deleteMany('table', {field1: 'value1'}, (err, doc) => {
        //TODO sth with err and doc
        //err means the error message 
    });
}
//传入回调函数的doc参数与使用await的返回值是相同的
//callback's parameter doc is equals to the await function's return's value
//他们都将会删除table表中key1字段值为value1的所有数据
//these will delete all data that meets the criteria

返回值(will return an object)

//this means delete successfully
return { status: 1, message: '批量删除成功' };
//this means delete failed, the reason is error message
return { status: 0, reason: error, message: '批量删除失败'}

_2._删除符合条件的第一个数据(Delete the first data that meets the criteria)

async function a(){
    //这将会删除table表中key1字段值为value1的第一个查询到的数据
    //第三个参数为可选配置项
    //this will delete the first data that meets the criteria
    //the third parameter is options you can add to the method
    await mongo.deleteOne('table', {field1: 'value1'}, {sort: {field2: 1}});
}
//or
function a(){
    //这将会删除table表中key1字段值为value1的第一个查询到的数据
    //第三个参数为可选配置项
    //this will delete the first data that meets the criteria
    //the third parameter is options you can add to the method
    mongo.deleteOne('teble', {field1: 'value1'}, {sort: {field2: 1}}, (err, doc) => {
        //TODO sth with err and doc
        //err means the error message
    })
}
//传入回调函数的doc参数与使用await的返回值是相同的
//callback's parameter doc is equals to the await function's return's value

可选项 options

  • sort: object - 设置排序,如果多条文档匹配查询条件,将影响到实际更新哪条文档(只会更新第一条)
  • sort: object - if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  • maxTimeMS: string - 对查询设置时间限制 - 需要 mongodb 2.6.0 及以上版本
  • maxTimeMS: string - set time limit for searching - Required MongoDB 2.6.0 and above version
  • rawResult: bool - 如果设置为 true,返回结果将是 MongoDB 驱动的原生结果
  • rawResult: bool - if set true, The return result will be the native result of the MongoDB drive

返回值(will return an object)

//(this means delete successfully)
return {status: 1, reason: undefined, message: '删除单条数据成功'};
//(this means delete failed, the reason is error message)
return {status: 0, reason: err, message: '删除单条数据失败'};

更新单个数据(update one data)

async function a(){
    //这将会更新查询到的第一条数据
    //第四个参数是可选配置项
    //this will update the first piece of data to the query
    //the last parameter is options you can add to the method
    await mongo.updateOne('table', {field: 'oldValue'}, {field1: 'newValue'}, {sort: {field2: 1}});
}
//or
function a(){
    //这将会更新查询到的第一条数据
    //第四个参数是可选配置项
    //this will update the first piece of data to the query
    //the last parameter is options you can add to the method
    mongo.updateOne('table', {field: 'oldValue'}, {field1: 'newValue'}, {sort: {field2: 1}}, (err, doc) => {
        //TODO sth with err and doc
        //err means error message
    })
}
//传入回调函数的doc参数与使用await的返回值是相同的
//callback's parameter doc is equals to the await function's return's value

可选配置项

  • new: bool - 如果设置为 true,不再返回旧文档而是更新后的文档。默认值 false(从 4.0 版本开始)
  • new: bool - If set to True, the old document is no longer returned, but the updated document. Default value False (starting from version 4.0)
  • upsert: bool - 如果文档不存在则插入一条新数据。默认值 false
  • upsert: bool - If the document does not exist, insert a new piece of data. Default Value False
  • fields: {Object|String} - 选择字段。等效于 .select(fields).findOneAndUpdate()
  • fields: {Object|String} - Select a field. Equivalent to .select(fields).findOneAndUpdate()
  • sort: bool - 如果查询条件匹配多条文档,可以设置排序条件以确定更新哪条文档(排序后的第一条)
  • sort: bool - if set true, The return result will be the native result of the MongoDB drive
  • maxTimeMS: string - 对查询设置时间限制 - 需要 mongodb 2.6.0 及以上版本
  • maxTimeMS: string - Set time limits for queries-requires MongoDB 2.6.0 and above versions
  • runValidators: bool - 如果值为 true,更新操作执行时会做 update validators 。 Update validators 会依照 model 的 schema 对更新操作做校验。
  • runValidators: bool - If the value is true, the update operation is performed when it is validators. Update validators will verify the updating operation according to the schema of the model.
  • setDefaultsOnInsert: bool - 如果该选项和 upsert 都是 true, mongoose 会在插入新文档时应用 schema 中指定的 默认值。该选项只会在 MongoDB 2.4 版本及以上生效,因为它依赖 MongoDB 的 $setOnInsert 操作符。
  • setDefaultsOnInsert: bool - If both the option and the Upsert are true, Mongoose applies the default value specified in the schema when a new document is inserted. This option will only take effect in the MongoDB 2.4 version and above because it relies on the $setOnInsert operator of MongoDB.
  • rawResult: bool - 如果值为 true,将返回 MongoDB 驱动的 原生结果(raw result)
  • rawResult: bool - If the value is true, the original result of the MongoDB driver (raw outcome) is returned
  • context: string - 如果设置为 "查询" 和运行验证程序处于打开状态, 这将引用更新验证运行的自定义验证函数中的查询。如果运行验证器是假的, 则不执行任何操作。
  • context: string - if set to 'query' and runValidators is on, this will refer to the query in custom validator functions that update validation runs. Does nothing if runValidators is false.

返回值(will return an object)

//(更新成功,result为更新后的该字段的对象)
//(update successfully, result is the one data which has updated)
return { status: 1, body: doc};
//(更新失败,reason是失败原因)
//(update failed, reason is error message)
return { status: 0, body: undefined, reason: error};

更新多条数据(update all matches data)

(async function a(){
    const doc = await mongo.updateMany('table', {matchKey: 'matchValue'}, {updateKey: 'updateValue'});
    //TODO with doc
    // doc.n Number  of documents matched
    // doc.nModified  Number of documents modified
})();
 
(function (){
    mongo.updateMany('table', {matchKey: 'matchValue'}, {updateKey: 'updateValue'}, (err, doc) => {
        //TODO with doc
        // doc.n      Number  of documents matched
        // doc.nModified  Number of documents modified
    });
})();
//您也可以在第四个参数处传入一个可选配置的对象
//You can also pass in an optionally configured object at the fourth argument
 

返回值(will return an object)

//更新成功 body为updateMany()返回对象,有以下属性
// doc.n      匹配的文档数
// doc.nModified  修改的文档数
// update successful 
// body.n      Number  of documents matched
// body.nModified  Number of documents modified
return {status: 1, body: doc};
//更新失败 reason是失败原因
//update failed , reason is the error message
return {status: 0, body: undefined, reason: err}

获取原生某表连接(get native connection for one collection)

const client = mongo.getClient('table');
//您可以自己构建诸如查询等逻辑语句
//You can build your own logical statements such as queries, eg.
//like this => 
client.find({name: 'leng'}).where('age').gt(20).limit(5).exec((err, doc) => {
    //TODO sth with err and doc
})

关闭数据库连接(close connection)

mongo.close();
//想再次连接数据库可以再次调用实例化方法,并且传入schema对象
// 如果想切换连接的数据库,则需要调用静态方法config()重新配置再调用实例化方法传入schema对象
// To connect to the database again, you can call the instantiation method again and pass in the schema object
// If you want to switch the connected database, you need to call static method Config () Reconfigure and then call the instantiation method to pass in the schema object

我会继续更新完善功能,GitHub的更新会晚于在npm的更新
I will continue to update and improve the features,and the GitHub update will be later than the update in NPM
如果有什么问题和建议,请给我发邮件到664930912@qq.com 或者 lfb15666280558@gmail.com

If you have some issues , send email to 664930912@qq.com or lfb15666280558@gmail.com

您也可以去www.lengfangbing.com点击右上方 给我留言 来给我留下您的意见等

Package Sidebar

Install

npm i node-mongoose

Weekly Downloads

0

Version

1.2.3

License

ISC

Unpacked Size

35.9 kB

Total Files

10

Last publish

Collaborators

  • lengfangbing