node.js - Mongoose 模式中的嵌套对象

标签 node.js mongodb mongoose-schema

我在这里看到了很多关于这个问题的答案,但我仍然不明白(可能是因为他们使用了更“复杂”的例子)...... 所以我试图做的是一个“客户”的模式,它将有两个嵌套的“子字段”字段,以及其他可能重复的字段。这就是我的意思:

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

telemail 可能是一个数组。 和地址不会重复,但有一些子字段,你可以看到。

我怎样才能做到这一点?

最佳答案

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 - Mongoose 模式中的嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39596625/

相关文章:

mongoose-schema - Mongoose Schema 静态与方法

node.js - 异步每个都会引入延迟

node.js - 从上一个意图中获取后续意图中的参数

mongodb - 不同副本集成员上的不同索引

mongodb show dbs listDatabases 失败

node.js - NodeJS 中的 Mongoose 模式类型错误 : Schema is not a constructor

node.js - 通过 mongoose 将嵌套对象结果从 MongoDB 获取到 Node 环境时出现问题

javascript - socket.io,如何从函数中获取事件名称?

javascript - 在 Node API 中接收完整日期时间而不是仅接收日期

spring - 从 Spring/MongoDB findAndModify 返回新旧实体