MongoDb - 具有空值的有界数组显示无界

时间:2016-01-23 20:48:15

标签: javascript node.js mongodb mongoose

在我对Mongodb和Mongoose的新手技巧中,我似乎在这项基本任务中惨遭失败。

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

创建时pets数组值为空,因为用户可以随身携带宠物。当我查看mongo控制台时,pets数组是无界的,没有字段。我也无法为数组添加值。

Mongoose Schema:

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" :"史密斯","用户名" :" bob123","宠物" :[]," __ v" :0}

修改数组时:

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')});
});

输出:

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)

1 个答案:

答案 0 :(得分:1)

MongoDB允许您limit the number of elements in an array。此功能也已在Mongoose中作为GameObject[] cubeObjectClones = new GameObject[mapLength]; for (int x = 0; x < mapLength; x++) { var instantiateMap = new Vector3(x * 2, 0, 1); cubeObjectClones[x] = Instantiate(cubeObject, instantiateMap, Quaternion.identity) as GameObject; cubeObjectClones[x].transform.parent = transform; } 查询的一部分实现。将元素添加到数组并限制其大小的步骤如下:

  1. 将元素推入数组。
  2. 切割阵列。
  3. 这段代码解释了如何使用Mongoose执行此操作:

    .update