我在这里看到了这个问题的许多答案,但我仍然不明白(可能是因为他们使用了更"复杂"的例子)...

let customerModel = new Schema({
    firstName: String,
    lastName: String,
    company: String,
    contactInfo: {
        tel: [Number],
        email: [String],
        address: {
            city: String,
            street: String,
            houseNumber: String
        }
    }   
});

telemail可能是一个array.

我怎样才能做到这一点?

推荐答案

const mongoose = require("mongoose");

// Make connection
// https://mongoosejs.com/docs/connections.html#error-handling
mongoose.connect("mongodb://localhost:27017/test", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

// Define schema
// https://mongoosejs.com/docs/models.html#compiling
const AddressSchema = mongoose.Schema({
  city: String,
  street: String,
  houseNumber: String,
});

const ContactInfoSchema = mongoose.Schema({
  tel: [Number],
  email: [String],
  address: {
    type: AddressSchema,
    required: true,
  },
});

const CustomerSchema = mongoose.Schema({
  firstName: String,
  lastName: String,
  company: String,
  connectInfo: ContactInfoSchema,
});

const CustomerModel = mongoose.model("Customer", CustomerSchema);

// Create a record
// https://mongoosejs.com/docs/models.html#constructing-documents
const customer = new CustomerModel({
  firstName: "Ashish",
  lastName: "Suthar",
  company: "BitOrbits",
  connectInfo: {
    tel: [8154080079, 6354492692],
    email: ["asissuthar@gmail.com", "contact.bitorbits@gmail.com"],
  },
});

// Insert customer object
// https://mongoosejs.com/docs/api.html#model_Model-save
customer.save((err, cust) => {
  if (err) return console.error(err);

  // This will print inserted record from database
  // console.log(cust);
});

// Display any data from CustomerModel
// https://mongoosejs.com/docs/api.html#model_Model.findOne
CustomerModel.findOne({ firstName: "Ashish" }, (err, cust) => {
  if (err) return console.error(err);

  // To print stored data
  console.log(cust.connectInfo.tel[0]); // output 8154080079
});

// Update inner record
// https://mongoosejs.com/docs/api.html#model_Model.update
CustomerModel.updateOne(
  { firstName: "Ashish" },
  {
    $set: {
      "connectInfo.tel.0": 8154099999,
    },
  }
);

Node.js相关问答推荐

赫斯基添加命令已弃用?

如何使用Nextjs路由从下一步/导航在新选项卡中通过";router.ush";打开链接

在内存中加载安全密钥安全吗?还是每次都从文件中读取?

仅在一次查询中 MongoDB 上最近的一对位置

我需要聚合两个 MongoDB 集合

错误:无法为 /blog 收集页面数据并且在 object.fetch 处获取失败

在 linux mint 上部署 node 应用程序的最简单方法是什么?

在 Header 中使用 Authorization 方法和新的附加参数:accessToken 有什么区别?

仅显示用户在 Reactjs 中使用服务器端发布的帖子是 Node Js、Mongodb

如何为一个网站实现这 2 个网址.即 www.administrator.sitename.com 和 www.sitename.com?

使用中的端口代码:'EADDRINUSE',即使在 kill 命令之后

来自 Node-aws 的 Dynamo Local:所有操作都失败无法对不存在的表执行操作

如何使用 Puppeteer 从输入中删除现有文本?

Node.js、Cygwin 和 Socket.io 走进一家wine 吧……Node.js 抛出 ENOBUFS,所有人都死了

Node.js + Express 上的多个视图路径

在 Mongoose 中创建外键关系

如何将子集合添加到 Firestore 中的文档?

如何在 node 中找到引用站点 URL?

如何创建安全(TLS/SSL)Websocket 服务器

nodemon + express,监听端口=?