关于javascript:MongoDb-具有空值的有界数组显示无界

MongoDb - bounded array with empty values shows unbounded

以我对Mongodb和Mongoose的新手技能,我似乎在这项基本任务上惨败。

我有10个元素的有界数组。一个用户只能养10只宠物,所以我想让它与设置的字段绑定,而空值是最好的方法。

pets数组的值在创建时为空白,因为用户可以随行添加宠物。当我在mongo控制台中查看时,pets数组不受限制,没有任何字段。我也无法将值添加到数组中。

猫鼬模式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var userSchema = new Schema({
  firstName: { type: String, required: true },
  lastName: { type: String, required: true },
  username: { type: String, required: true, unique: true },
  location: String,
  created_at: Date,
  pets: [
    {"pet0": {} },
    {"pet1": {} },
    {"pet2": {} },
    {"pet3": {} },
    {"pet4": {} },
    {"pet5": {} },
    {"pet6": {} },
    {"pet7": {} },
    {"pet8": {} },
    {"pet9": {} }
  ]
});

mongodb:

{"_id" : ObjectId("56a3e324bdebcf801c1ca224"),"firstName" :"bob","lastName" :"smith","username" :"bob123","pets" : [ ],"__v" : 0 }

修改数组时:

1
2
3
4
UserModel.findOne({ firstName:"bob" }, 'pets', function(err, user) {
    user.pets[0] = {"name":"felix","type":"cat" }
    user.save(function(err) { console.log(err); console.log('saved')});
});

输出:

1
2
3
4
5
6
7
8
9
10
11
Mongoose: users.findOne({ firstName: 'bob' }) { fields: { pets: 1 } }  
null
/home/one/github/foo/node_modules/mongoose/lib/schema/documentarray.js:100
      doc.validate({ __noPromise: true }, function(err) {
          ^
TypeError: undefined is not a function
    at /home/one/github/foo/node_modules/mongoose/lib/schema/documentarray.js:100:11
    at DocumentArray.SchemaType.doValidate (/home/one/github/foo/node_modules/mongoose/lib/schematype.js:654:22)
    at DocumentArray.doValidate (/home/one/github/foo/node_modules/mongoose/lib/schema/documentarray.js:78:35)
    at /home/one/github/foo/node_modules/mongoose/lib/document.js:1156:9
    at process._tickCallback (node.js:355:11)

MongoDB允许您限制数组中的元素数量。 Mongoose中还作为.update查询的一部分实现了此功能。将元素添加到数组并限制其大小的步骤如下:

  • 将元素推入数组。
  • 切片数组。
  • 此代码段说明了如何使用Mongoose进行此操作:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    UserModel.findOne({ firstName:"bob" }, function(err, user) {
      UserModel.update(user, {
        $push: {
          pets: {
            $each: [{ name:"felix", type:"cat" }],
            $slice: -10
          }
        }
      }, function(err, numAffected) {
        if (err) console.log(err);
        console.log('updated');
      });
    });