将 Mongo ObjectId 保存到另一个文档中
Save a Mongo ObjectId into another document
我正在研究 commenting system saved into Mongo,建议采用以下结构:
{
_id: ObjectId(...),
discussion_id: ObjectId(...),
slug: '34db',
posted: ISODateTime(...),
author: {
id: ObjectId(...),
name: 'Rick'
},
text: 'This is so bogus ... '
}
我想将author.id
保存为用户评论的ObjectId
,我在请求中有这个值req.user._id
我的 Comment 模型需要什么数据类型才能接受这个值?
我试过了:
const authorSchema = new Schema({
id: ObjectId,
username: String
});
但这给出了 ReferenceError: ObjectId is not defined
我看到了ObjectId listed as a valid Schema type但是,它只有在自动生成时才会出现。
将评论中的 user._id
ObjectId 存储为 author.id
的正确方法是什么,或者是否有更好的方法来完全存储引用?
所以您必须通过从 Mongoose 获取它来在您的架构文件中定义 ObjectId。
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ObjectId = Schema.Types.ObjectId;
文档中有完整的引用示例here
我正在研究 commenting system saved into Mongo,建议采用以下结构:
{
_id: ObjectId(...),
discussion_id: ObjectId(...),
slug: '34db',
posted: ISODateTime(...),
author: {
id: ObjectId(...),
name: 'Rick'
},
text: 'This is so bogus ... '
}
我想将author.id
保存为用户评论的ObjectId
,我在请求中有这个值req.user._id
我的 Comment 模型需要什么数据类型才能接受这个值?
我试过了:
const authorSchema = new Schema({
id: ObjectId,
username: String
});
但这给出了 ReferenceError: ObjectId is not defined
我看到了ObjectId listed as a valid Schema type但是,它只有在自动生成时才会出现。
将评论中的 user._id
ObjectId 存储为 author.id
的正确方法是什么,或者是否有更好的方法来完全存储引用?
所以您必须通过从 Mongoose 获取它来在您的架构文件中定义 ObjectId。
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ObjectId = Schema.Types.ObjectId;
文档中有完整的引用示例here