Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/388.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 向文档mongodb添加新字段_Javascript_Mongodb_Meteor - Fatal编程技术网

Javascript 向文档mongodb添加新字段

Javascript 向文档mongodb添加新字段,javascript,mongodb,meteor,Javascript,Mongodb,Meteor,我对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

我对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>
}
//newProfile是一个对象,它包含的一个字符串称为school
if(Schools.find({name:newProfile.school}).fetch().length!=1){
var学校={
姓名:newProfile.school
}
Meteor.call(“新闻学校”,学校);
//方法1(不起作用)
var schoolDoc=Schools.findOne({name:newProfile.school});
更新({u-id:schoolDoc.{u-id},{$set:{注册学生:Meteor.user()}});
//方法2?
//更新(_id:,{$push:{注册学生:Meteor.user()}});
}
否则{
//学校。更新。。。
}
如果列出的学校不存在,我将创建一个新的学校文档。学校需要保存一个学生数组/列表(这就是我遇到的问题)。如何将学生添加到新字段(称为Enrolled students)


谢谢

对于您尝试执行的操作,无需获取
\u id
。当您使用
update
时,只需将
{{u id:schoolDoc.\u id}
与查询一起切换即可。看起来使用
{name:newProfile.school}
是可行的,假设代码的其余部分做了您希望它做的事情

虽然正常的Mongo驱动程序也可以这样做,但我发现Meteor不允许您的更新查询是
\u id

首先,确保您正在提取正确的文档,您可以尝试以下方法:

var school_id = Schools.findOne({name: newProfile.school})._id;
Schools.update({_id: school_id}, { $push: { enrolledStudents: Meteor.user()}});
// 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 {

}

如果这不起作用,您将不得不进行一些调试,以查看它的哪些方面不起作用。

我很难准确理解您要做的事情。以下是我到目前为止的分析和理解,并提出了几点建议:

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的异步性。请致电客户端

尝试这样做:

var school_id = Schools.findOne({name: newProfile.school})._id;
Schools.update({_id: school_id}, { $push: { enrolledStudents: Meteor.user()}});
// 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。

执行此操作时,web控制台中出现错误“ThrowifSelectorsNotID”您使用的是常规节点Mongo驱动程序、Mongoose还是其他什么?您使用的是meteor Mongo驱动程序。meteor不允许客户端更新,除非通过_id进行更新。
ThrowifSelectorsNotId
错误是因为EmptyAsenal的答案中存在键入错误。添加“{”和“}'关于
\u id:school\u id
部分。确实缺少花括号,但错误与之前的查询有关。嗨,戴夫,谢谢你的帮助。要澄清…Meteor.call('newSchool',school')正在调用名为newSchool的Meteor方法,该方法在学校集合中创建新文档。第一个“if”语句检查学校集合中是否存在该学校,如果不存在,请使用当前用户学校创建该学校。第二部分(我遇到问题)一旦创建了学校,我如何添加第一个用户和以后要加入的任何其他用户?我正在尝试使用Schools.update({…})将初始学生和未来学生添加到正确的学校文档中。