Nodejs中mongodb字段类型ObjectID
Nodejs中mongodb字段类型ObjectID
我用的mongoose框架,一个表的外键是ObjectID类型,不能往这个字段插入数字1,有什么办法吗?
Node.js 中 MongoDB 字段类型 ObjectID
在使用 Mongoose 框架时,你可能会遇到需要处理 ObjectID
类型字段的情况。ObjectID
是 MongoDB 的默认主键类型,用于确保每个文档都有一个唯一的标识符。如果你尝试将一个非 ObjectID
类型的数据(如数字)插入到一个定义为 ObjectID
类型的字段中,Mongoose 会抛出错误。
示例代码
假设你有一个 User
模型,其中包含一个引用其他集合的外键字段 profileId
,并且该字段类型为 ObjectID
。
const mongoose = require('mongoose');
const { Schema } = mongoose;
// 定义 Profile 模型
const profileSchema = new Schema({
name: String,
});
const Profile = mongoose.model('Profile', profileSchema);
// 定义 User 模型
const userSchema = new Schema({
name: String,
profileId: { type: Schema.Types.ObjectId, ref: 'Profile' },
});
const User = mongoose.model('User', userSchema);
插入数据
当你尝试向 profileId
字段插入一个数字(例如 1
),将会导致错误。正确的做法是插入一个有效的 ObjectID
。
// 错误的插入方式
const newUser = new User({
name: 'John Doe',
profileId: 1 // 这里应该是一个有效的 ObjectID
});
// 正确的插入方式
const newProfile = new Profile({ name: 'John Profile' });
newProfile.save().then(savedProfile => {
const newUser = new User({
name: 'John Doe',
profileId: savedProfile._id // 使用已保存的 Profile 的 _id
});
newUser.save()
.then(savedUser => console.log('User saved:', savedUser))
.catch(err => console.error('Error saving user:', err));
}).catch(err => console.error('Error saving profile:', err));
解释
-
ObjectID: 每个 MongoDB 文档都自动带有
_id
字段,默认类型为ObjectID
。它是一个 12 字节的 BSON 数据类型,通常用于唯一标识文档。 -
ref 属性: 在 Mongoose 模型中,
ref
属性用于关联其他集合。在这个例子中,profileId
引用Profile
集合中的文档。 -
插入数据: 当你插入数据时,必须确保
profileId
字段包含的是一个有效的ObjectID
。直接插入数字会导致类型不匹配错误。
通过上述示例,你可以看到如何正确地使用 ObjectID
类型,并避免常见的类型不匹配错误。
ObjectID 有一定的格式, 你不能只插入數字1 http://docs.mongodb.org/manual/reference/object-id/
你可以保留_id, 然後自己再新增一個field, 或是你不想用ObjectID, 可以在Schema改成String 或是 Number, 例如:
var statusSchema = new mongoose.Schema({
_id: { type: String },
name: { type: String, default: '' }
});
可以自己创建一个objectid var id = new mongoose.Schame.ObjectId() ; 这样你在做关联保存什么的就可以直接使用这个新建的id了。 也可以使用回调来获取刚刚保存的对象的id信息而不用新建一个。
不知道你描述的objectid场景是不是这样http://www.9958.pw/post/mongodb_objectid
你都已经声明成ObjectId类型了,然后在赋1是什么意思呢?本身这种想法就是错误的
在Node.js中使用Mongoose框架时,ObjectId
类型用于表示MongoDB中的文档ID。如果你尝试向一个 ObjectId
类型的字段插入非 ObjectId
的值(例如数字 1
),Mongoose会抛出错误。
示例代码
假设你有一个集合 User
和一个集合 Post
,并且每个 Post
都有一个外键 userId
指向 User
的 _id
:
const mongoose = require('mongoose');
const { Schema } = mongoose;
// 定义 User 模型
const userSchema = new Schema({
name: String,
});
const User = mongoose.model('User', userSchema);
// 定义 Post 模型,并且包含一个外键 userId
const postSchema = new Schema({
title: String,
userId: {
type: Schema.Types.ObjectId,
ref: 'User',
},
});
const Post = mongoose.model('Post', postSchema);
// 连接数据库
mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });
// 创建用户
async function createUser() {
const newUser = new User({ name: 'John Doe' });
await newUser.save();
}
// 创建帖子并关联用户
async function createPost() {
const post = new Post({
title: 'My First Post',
userId: '5f9c9e7f2b3a4c5d6e7f8b9c' // 假设这是某用户的 _id
});
try {
await post.save();
console.log('Post saved successfully');
} catch (error) {
console.error('Error saving post:', error);
}
}
// 运行函数
createUser().then(createPost);
解释
ObjectId
: 是一个字符串格式的12字节UUID(通用唯一识别码)。Mongoose会自动处理这些ID。- 错误处理: 在尝试向
ObjectId
字段插入非ObjectId
值时,Mongoose会抛出错误。你需要确保插入的数据类型正确。 - 参考 (
ref
): 当你定义userId
字段时,通过ref
指定它引用的是哪个模型,这样可以在查询时方便地获取相关联的数据。
如果你尝试插入 userId: 1
,将会导致错误。你应该确保插入的是一个有效的 ObjectId
字符串。