before

node搭建的博客继续做下去当毕设了,半年前做的了,忘的七七八八,诶学了还是得好好记录。

连接

1
mongoose.connect('mongodb://127.0.0.1:27017/nodeBlog');

find

在qaModel中直接find,得到的user是它的id,用populate转一下,得到的就是user的Object了

1
2
3
qaModel.find().populate('user').exec(function (err, qa) {
console.log(arguments);
});

如果再下一级的转换就 populate('answer.user')

update

使cb中的值是更新后的对象

1
userModel.findByIdAndUpdate(user._id,{$set:{local:req.body.value}},{new:true},callback);
  • In Mongoose 4.0, the default value for the new option of findByIdAndUpdate (and findOneAndUpdate) has changed to false (see #2262 of the release notes). This means that you need to explicitly set the option to true to get the new version of the doc

    所以要加上option 参数{new:true} 保证callback中的参数是更新后的对象

  • 1
    2
    3
    4
    5
    A.findByIdAndUpdate(id, update, options, callback) // executes
    A.findByIdAndUpdate(id, update, options) // returns Query
    A.findByIdAndUpdate(id, update, callback) // executes
    A.findByIdAndUpdate(id, update) // returns Query
    A.findByIdAndUpdate() // returns Query

嵌套结构里的更新

数据的结构如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//question schema一条数据的结构
{
"_id" : ObjectId("58f575bb09c601c45f6c2819"),
"title" : "ionic开发app 对于用户登录信息的存储用怎样的方案比较好",
"content" : "第一次接触...",
"user" : ObjectId("58a934b9a3785c0e8b4c92ef"),
"answers" : [
{
"creatAt" : ISODate("2017-04-18T02:11:22.086Z"),
"up" : 0,
"upuser" : [],
"_id" : ObjectId("58f575ca09c601c45f6c281a"),
"user" : ObjectId("58a934b9a3785c0e8b4c92ef"),
"content" : "因为在..."
},
{
"creatAt" : ISODate("2017-04-18T02:13:02.097Z"),
"up" : 0,
"upuser" : [],
"_id" : ObjectId("58f5762ec85325c466d32bb6"),
"user" : ObjectId("58a934b9a3785c0e8b4c92ef"),
"content" : "123"
}
],
"creatAt" : ISODate("2017-04-18T02:11:07.534Z"),
"__v" : 0
}
1
2
3
4
var setdata = {"answers.$.up":req.body.up};
qaModel.update({"answers._id":req.body._aid},{$set:setdata},function (err, result) {
...
});

如果知道这个要修改的answer在answers数组中的index,可以用answers.index.up来更新,现在不知道索引,就使用 $ 来占位, Filter用{answers._id:xxx} update用{answers.$.up:xxx}