【问题标题】:Mongoose - why isn't subdocument working?Mongoose - 为什么子文档不起作用?
【发布时间】:2018-05-02 22:02:07
【问题描述】:

我正在制作一个投票应用程序,我想保存根据用户 ID、IP 地址或 MAC 地址对投票进行投票的用户。

我认为在我的 Poll 模型中添加 voted: VotedSchema 属性会很简单,但由于某种原因它无法正常工作。

投票模型:

const mongoose = require('mongoose');
const { Schema } = mongoose;
const OptionSchema = require('./Option');
const VotedSchema = require('./Voted');

const pollSchema = new Schema({
  title: String,
  options: [OptionSchema],
  dateCreated: { type: Date, default: Date.now() },
  _user: { type: Schema.Types.ObjectId, ref: 'User' },
  voted: VotedSchema
});

mongoose.model('polls', pollSchema);

投票子文档:

const mongoose = require('mongoose');
const { Schema } = mongoose;

const votedSchema = new Schema({
  userID: [String],
  IPaddress: [String],
  MACaddress: [String]
});

module.exports = votedSchema;

另一方面,如果我不使用子文档,那么它就可以正常工作:

const mongoose = require('mongoose');
const { Schema } = mongoose;
const OptionSchema = require('./Option');
const VotedSchema = require('./Voted');

const pollSchema = new Schema({
  title: String,
  options: [OptionSchema],
  dateCreated: { type: Date, default: Date.now() },
  _user: { type: Schema.Types.ObjectId, ref: 'User' },
  voted: {
    userID: [String],
    IPaddress: [String],
    MACaddress: [String]
  }
});

mongoose.model('polls', pollSchema);

我在这里错过了一些超级简单的东西吗?这个问题让我有点困惑。

【问题讨论】:

  • 您能否澄清一下,在引用的子文档的情况下不工作是什么意思?

标签: node.js mongoose model subdocument


【解决方案1】:

这还没有在猫鼬中实现。

看看这个。

https://github.com/Automattic/mongoose/pull/585

现在,如果您愿意,您可以照常执行第二个选项。

或使用

VotedSchema.TypeVotedSchema.tree

可以通过数组来嵌入文档。

投票:[VotedSchema]

http://mongoosejs.com/docs/subdocs.html#single-embedded

【讨论】:

  • 这有帮助吗?
猜你喜欢
  • 1970-01-01
  • 2018-08-11
  • 2021-03-30
  • 2013-12-28
  • 1970-01-01
  • 2019-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多