【问题标题】:Mongoose how to save document inside an arrayMongoose如何将文档保存在数组中
【发布时间】:2016-12-26 23:56:15
【问题描述】:

我有一个看起来像这样的模型:

User.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var memberSchema = new Schema({
        email: { 
            type: String, 
            required: true, 
            unique: true 
        },
        password: { 
            type: String, 
            required: true,
            min: 8
        }
});

var userSchemaPrimary = new Schema({
    team_code : {
        type: String, 
        required: true, 
        unique: true 
    },
    members:[memberSchema],
});
var User = mongoose.model('User', userSchemaPrimary);

module.exports = User;

这就是我尝试保存的方式

var User = require('../models/user');
var newTeam = new User({
    team_code : 'CODE01',
    members:
        {
            email: req.body.email,
            password: pass
        }
});

newTeam.save(function(err) {
    if (err) throw err;
    console.log('User saved successfully!');
    return res.send("Done");
});

执行时,抛出模型验证错误。 好吧,我尝试在没有数组文档的情况下保存数据,然后成功保存。但是当我尝试保存数组(数组“成员”)时,会引发验证错误。

我想要

按以下方式存储数据:

{
   team_code: "CODE01",
   members: [
      {
         email: "test01@email.com",
         password: "11111111"
      },
      {
         email: "test02@email.com",
         password: "22222222"
      }
      {
         email: "test03@email.com",
         password: "33333333"
      }
   ]
}

我不明白出了什么问题。任何帮助表示赞赏。

【问题讨论】:

  • password Schema 中的字段是字符串,但是你保存的是数字,也许这是个问题
  • 不不,这只是我给出的一个例子,正在保存字符串

标签: arrays node.js mongodb mongoose mongoose-schema


【解决方案1】:

您正在将对象分配给members 字段,但它是一个数组

var newTeam = new User({
    team_code : 'CODE01',
    members: [{
            email: req.body.email,
            password: pass
    }] // <-- note the array braces []
});

【讨论】:

  • 那么解决办法是什么?
猜你喜欢
  • 2022-10-01
  • 2017-10-06
  • 1970-01-01
  • 2013-09-20
  • 2018-08-02
  • 1970-01-01
  • 2012-05-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多