mongoose操作

善用文档mongoose
mongodb

1. mongoose中使用promise

Mongoose async operations, like .save() and queries, return Promises/A+ conformant promises.

  • 使用mongoose的异步操作,比如saveupdate,create会自动返回Promise对象

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    var gnr = new Band({
    name: "Guns N' Roses",
    members: ['Axl', 'Slash']
    });
    var promise = gnr.save();
    assert.ok(promise instanceof require('mpromise'));
    promise.then(function (doc) {
    assert.equal(doc.name, "Guns N' Roses");
    });
  • queries不是标准的Promise但是有then方法,可以使用exec(),返回Promise对象。比如find前缀的find,.findOneAndRemovefindOne

(只要返回类型是query的话,就可以执行exec方法,不执行就返回的是model自身,可以继续用其他的API)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var query = Band.findOne({name: "Guns N' Roses"});
assert.ok(!(query instanceof require('mpromise')));
// A query is not a fully-fledged promise, but it does have a `.then()`.
query.then(function (doc) {
// use doc
});
// `.exec()` gives you a fully-fledged promise
var promise = query.exec();
assert.ok(promise instanceof require('mpromise'));
promise.then(function (doc) {
// use doc
});

2. 外键

使用mongoose.Schema.Types.ObjectId定义外键

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var personSchema = Schema({
_id : Number,
name : String,
age : Number,
stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
var storySchema = Schema({
_creator : { type: Number, ref: 'Person' },
title : String,
fans : [{ type: Number, ref: 'Person' }]
});
var Story = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);

查找时使用populate可以同时取出外键内容

1
2
3
4
5
6
7
8
9
// 查找title为Once upon a timex的story,同时找出_creator的具体内容
Story
.findOne({ title: 'Once upon a timex.' })
.populate('_creator')
.exec(function (err, story) {
if (err) return handleError(err);
console.log('The creator is %s', story._creator.name);
// prints "The creator is Aaron"
});

可以进行进一步的条件查找

1
2
3
4
5
6
7
8
9
Story
.find(...)
.populate({
path: 'fans',
match: { age: { $gte: 21 }},
select: 'name -_id',
options: { limit: 5 }
})
.exec()

3. 使用pull和push移除数组中的项

document Array操作

在我删除博客文章的时候需要移除标签里的文章列表的对应项
使用pull移除
doc.array.pull({ _id: 'someId' })
还有push添加
doc.subdocs.push({ _id: 4815162342 })

4. 条件查找

Comparison Query Operators

  • $eq : 找出全部等于某个值的 { <field>: { $eq: <value> } }等价于{ field: <value> }.
  • $gt : > 大于的 {field: {$gt: value} }
  • $gte : >=
  • $lt : <
  • $lte : <=
  • $ne : !==
  • $in : 匹配数组中符合的项 { field: { $in: [<value1>, <value2>, ... <valueN> ] } }
  • $nin : 匹配数组中不符合的项

Mongoose学习参考文档——基础篇