[英]Add a new field to all documents of a collection with the value from the document field into MongoDB (Mongoose) with records of 300K+
[英]Add a new field to a document mongodb
我对mongodb并不陌生,并且遇到了一个基本问题。 如何获取已经创建的文档的ID字段? 我需要ID,以便我可以向文档更新/添加新字段。
//newProfile is an object, one string it holds is called school
if(Schools.find({name: newProfile.school}).fetch().length != 1){
var school = {
name: newProfile.school
}
Meteor.call('newSchool', school);
//Method 1 (doesn't work)
var schoolDoc = Schools.findOne({name: newProfile.school});
Schools.update({_id: schoolDoc._id}, {$set: {enrolledStudents: Meteor.user()}});
//Method 2?
//Schools.update(_id: <what goes here?>, {$push: {enrolledStudents: Meteor.user()}});
}
else {
//Schools.update... <add users to an existing school>
}
如果列出的学校尚不存在,我将创建一个新的学校文件。 学校需要保存一系列学生列表(这是我遇到麻烦的地方)。 如何将学生添加到NEW字段(称为enrolledStudents)?
谢谢!
对于您要尝试执行的操作,无需获取_id
。 使用update
,只需在查询中{_id: schoolDoc._id}
。 假设您其余的代码完成了您想要的工作,那么使用{name: newProfile.school}
看起来就可以了。
虽然可以使用普通的Mongo驱动程序,但我看到Meteor不允许您的更新查询使用_id
: Meteor抛出throwIfSelectorIsNotId异常
首先,请确保您要提取正确的文档,然后可以尝试执行以下操作:
var school_id = Schools.findOne({name: newProfile.school})._id;
Schools.update({_id: school_id}, { $push: { enrolledStudents: Meteor.user()}});
如果这不起作用,则必须进行一些调试以查看特别是什么不起作用。
我在准确了解您要执行的操作时遇到了一些麻烦。 到目前为止,这里是我的分析和理解,并附带了一些建议:
if(Schools.find({name: newProfile.school}).fetch().length != 1){
这样会更有效
if(Schools.find({name: new Profile.school}).count() != 1) {
Meteor.call('newSchool', school);
不知道您在这里做什么,除非您将异步运行,这意味着到该代码块的其余部分执行Meteor.call()
函数可能尚未在服务器端完成。
//Method 1 (doesn't work)
var schoolDoc = Schools.findOne({name: newProfile.school});
Schools.update({_id: schoolDoc._id}, {$set: {enrolledStudents: Meteor.user()}});
根据代码顶部的if语句判断,数据库中有不止一个学校使用此名称。 所以我不确定schoolDoc
变量是否是您要查询的记录。
我相信您由于Meteor.call在客户端上的异步特性而遇到麻烦。
尝试做这样的事情:
// include on both server and client
Meteor.methods({
newSchool: function (school) {
var newSchoolId,
currentUser = Meteor.user();
if (!currentUser) throw new Meteor.Error(403, 'Access denied');
// add some check here using the Meteor check/match function to ensure 'school'
// contains proper data
try {
school.enrolledStudents = [currentUser._id];
newSchoolId = Schools.insert(school);
return newSchoolId;
} catch (ex) {
// handle appropriately
}
}
});
// on client
var schoolExists = false;
if (Schools.findOne({name: newProfile.school})) {
schoolExists = true;
}
if (schoolExists) {
var school = {
name: newProfile.school
};
Meteor.call('newSchool', school, function (err, result) {
if (err) {
alert('An error occurred...');
} else {
// result is now the _id of the newly inserted record
}
})
} else {
}
在客户端和服务器上都包含该方法,Meteor可以进行延迟补偿并立即在客户端上“模拟”插入,而无需等待服务器往返。 但是您也可以将方法保留在服务器端。
您应该在服务器上执行enrolledStudents部分,以防止恶意用户破坏您的数据。 另外,您可能不希望将整个用户对象实际存储在enrolledStudents数组中,仅存储用户_id。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.